3.7 Standard checks
There are a number of standard checks available within Code Checker for MATLAB. These can be enabled and configured as described in Chapter
Configuration Editor↓. The checks are explained in the following sections. For every standard check, an exemption tag is given. For more information about this, see Section
3.9↓. If a check fails, its results hold the following information:
-
A relative path from the root folder to the file in which the violation was encountered.
-
The part of the code that violates the coding standards including a link.
-
The scope of the failing feature/variable (if appliccable).
-
A message stating why the check failed at that location.
-
A link for quickly adding an exemption for the violation.
-
Rule information.
-
Configured check and parameter values.
Note: In the HTML report at most one violation of the same type per line of code will be shown for several checks, this is indicated per check in the following sections.
3.7.1 checkAbstractClassInstantiation
This checks if any abstract classes are instantiated in the code that is checked. Running the code would result in an error, because abstract classes cannot be instantiated.
Exemption tag: %@ok<ABSCI>
3.7.2 checkArgumentsBlockUsed
Checks whether an
arguments block is used for
input validation for the specified categories of functions among the files selected for checking. The
arguments block
introduced in MATLAB R2019b is very useful for input argument validation and can also be used for automatic casting. It provides a more readable and more performant alternative to functions such as
inputParser,
narginchk,
nargin and
varargin. If your code does not need to support older MATLAB releases, you might want to enable this check. Its parameters facilitate only checking publicly available functions for the presence of an
arguments block. This check ignores functions that:
-
Have no input arguments.
-
Are local (subfunctions), including any functions in a script.
-
Are nested. These are not allowed to have arguments blocks anyway.
-
Have all their inputs ignored (with the ~-notation).
If a function only uses arguments blocks with the Output attribute (introduced in MATLAB R2022b), the function is reported as a violation.
Configurable parameters
-
OnlyPublicFunctions (boolean): Set this to true (default) to only check if public, visible functions and methods use arguments blocks. In addition to the list above, enabling this parameter makes the check ignore:
-
Functions in a private folder.
-
Methods with any access restriction.
-
Hidden methods.
-
Getterand setter methods.
If the function is a method in a separate file and its class information could not be obtained (usually because of an error in the classdef file or while initializing its property values), the function will be checked and reported if there is no arguments block.
-
IgnoreSingleInputOrdinaryMethods (boolean): Set to true (default) to have this check ignore all ordinary (non-static) methods with a single input (one or more objects) that are not constructors. Adding an arguments block for these types of methods is generally not needed, and this parameter helps to prevent reporting unnecessary violations.
-
ExemptFolders (list): A list of folder-names whose files should be ignored by this check. This can be useful, for example, if you have a package folder that is not for public use. The folders of this parameter are checked for at the end of the path of a checked file. This means that specifying test as an exempt folder, makes this check ignore
C:\somefolder\test\myFile.m, but it will still check C:\test\somefolder\myFile.m and C:\somefolder\foldertest\myFile.m.
Alternatively, you can provide multiple layers for one folder. By specifying test\+internal as an exempt folder, you ignore C:\test\+internal\myFile.m, but will still check
C:\otherFolder\+internal\myFile.m and C:\test\myFile.m. By default, the list is empty.
Exemption tag: %@ok<CARBU>
3.7.3 checkAssertInputs
This checks if all calls to assert have an ID and a message as second and third inputs. These inputs can improve readability by showing the reader what it means if the assert fails. Additionally, the feedback to the user on a failed assertion will be much more informative.
Exemption tag: %@ok<ASINP>
3.7.4 checkAvoidComments
This checks if undesired phrases like, for example, ’% TODO’ and ’% WRONG’ are present in the comments of your code. Such comments reduce the readalibity of the code and increase the uncertainty of readers and maintainers. This check only searches for the phrases at the start of comments.
Configurable parameter
-
AvoidComments (list): A list of phrases that are to be avoided in comments.
Exemption tag: %@ok<AVCOM>
3.7.5 checkAvoidFunctions
Checks if the code depends on functions that should be avoided. For example: using eval is often discouraged because it can result in code that is unreliable and difficult to read. Other reasons to discourage use of certain functions and keywords are to prevent system damage or to ensure automation or code generation. You can also specify entire MATLAB folders to avoid using functions from.
Configurable parameters
Exemption tag: %@ok<AVFUN>
3.7.6 checkAvoidNames
Checks if the code uses names not to use for classes, functions and variables etcetera. For example: using myFunc or temp is often discouraged because it is not descriptive and it gives the impression that work is still under construction.
Configurable parameters
-
AspectsToCheck (list): A list of aspects to check, classes, functions, variables etcetera.
-
AvoidNames (list): A list of names that are to be avoided.
-
ReportCaseSensitive (boolean) : Set to true to report case-sensitive matches for ’AvoidNames’, the default value for this parameter is true.
-
AvoidRegexps (list): A list of regular expressions that are to be avoided. More information about regular expressions can be found here.
Exemption tag: %@ok<AVNAM>
3.7.7 checkAvoidVararginout
Checks if the code uses varargin and varargout as variable length input and output argument list. Avoiding the use of these variable length arguments increases the readability of the code.
Configurable parameters
-
AvoidVarargin (boolean) : Set to true to report the usage of varargin, the default value for this parameter is true.
-
AvoidVarargout (boolean): Set to true to report the use of varargin, the default value for this paramter is true.
Exemption tag: %@ok<VARIO>
3.7.8 checkBlockComment
Checks if any comment blocks are used. These may not be recommended because they could comment out more or less than you want. The comment blocks are recognized by ’%{’ and ’%}’ on a line (optionally surrounded by whitespace).
Exemption tag: %@ok<BLCKC>
3.7.9 checkBuiltinFunctionCompatibility
Checks if all MATLAB-installed functions that are used by the checked code were introduced before or at the first supported MATLAB release of the code. For example, if your configuration states that the first supported MATLAB release is R2016b, this check will report all calls to MATLAB-installed functions that were introduced in R2017a and later. It is advised to run this check on the most recent MATLAB release you have available to see the best results (see the limitation).
-
FirstSupportedRelease (string): Can be any value between 2006a and 2021a. The default value is 2017b.
-
ViolationUniqueness(list): Specify if you want to see unique violations global, per file or all violations. By default, this parameter is set to All.
-
Code Checker for MATLAB can only detect calls to MATLAB-installed functions if they were at least introduced in the MATLAB release you are currently using. Consider a parameter configuration that specifies that the checked code must run on R2016b. Calls to functions introduced in R2018b will only be detected as MATLAB-installed functions if Code Checker for MATLAB is run on R2018b or later. This means that running this check using MATLAB R2016b will not result in a violation for that MATLAB-installed function.
Exemption tag: %@ok<BFCNC>
3.7.10 checkCharacterArray
Checks the usage of character arrays. If one intends to use strings instead of character arrays, an overview of where character arrays are used is provided. The maximum number of reported character arrays per line is one. This does not report using outputs of MATLAB-installed functions that return character arrays. For example: mfilename or datestr. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Exemption tag: %@ok<CHARA>
3.7.11 checkCodeInterpretable
Report files that cannot be interpreted by MATLAB due to invalid code. Files might contain a parse error or have invalid characters. These files will be reported by this check, since files should not contain an error. Files with errors are also listed in the summary as described in Section
3.6.1↑.Note that it is not possible to add an exemption for this check since there’s no reason to allow invalid code.
3.7.12 checkCodeLength
Checks the length of the code where only executable lines of code are taken into account. Possible arguments blocks do not count towards the number of lines in a function. Limiting the length of functions increases the readability of the code.
Configurable parameters
-
MaxMainFuncLength (double): The maximum length for the main function. The default value for this parameter is 100 and it can be changed to anywhere between 10 and 500.
-
MaxSubFuncLength (double):The maximum length for a sub-function. The default value for this parameter is 50 and it can be changed to anywhere between 10 and 100.
-
MaxNestFuncLength (double): The maximum length for a nested function. The default value for this parameter is 10 and it can be changed to anywhere between 5 and 100.
-
MaxConstructLength (double): The maximum length for a constructor. The default value for this parameter is 100 and it can be changed to anywhere between 10 and 500.
-
MaxMethodLength(double): The maximum length for a method in a classdef file, methods in a separate file are treated as main function. The default value for this parameter is 10 and it can be changed to anywhere between 5 and 100.
Exemption tag: %@ok<COLEN>
3.7.13 checkCoderCompatibilityFunctionCalls
Reports the MATLAB-installed functions used in the code that are (partially) MATLAB Coder-compatible or not. Three levels of support for C/C++ code generation can be reported: Fully supported, supported with limitations, and not supported. The violations in the report contain links to the documentation of the MATLAB-installed functions so that you can easily check the limitations (if any) or find alternatives that are (more) Coder-compatible.
Configurable parameters
-
SupportLevel (string): Allowed values are:
-
Supported: Reports calls to MATLAB-installed functions that are Coder-compatible without limitations or sidenotes. Using this setting makes it so that the check does not fail (since only supported features are reported). This means that in order to see the results for this check when this parameter value is used, you have to enable Include passed checks in the Report tab of the GUI.
-
Supported with limitations: Reports calls to MATLAB-installed functions that are Coder-compatible with limitations or sidenotes. The link to the documentation provided in the report can help you to quickly find these limitations and act accordingly.
-
Unsupported: Reports calls to MATLAB-installed functions without support for C/C++ code generation. The link to the documentation provided in the report may help you to find alternatives for these functions that are Coder-compatible.
-
Release (string): The MATLAB release for which you would like to check Coder-compatibility. Allowed values are ’R2017b’ through ’R2021a’ and ’MostRecent’. The ’MostRecent’ option automatically applies the level of Coder-compatibility of the most recent MATLAB release supported by Code Checker for MATLAB.
-
ViolationUniqueness(list): Specify if you want to see unique violations global, per file or all violations. By default, this parameter is set to All.
If you would like to see the level of Coder-compatibility for every MATLAB-installed function call, you can configure this check multiple times, but with different settings for the
SupportLevel parameter. That way, the report generated after the check contains a separate table for each of the support levels. For more information on configuring the same check multiple times, see Section
Multiple configurations per check↑.
This check only reports known MATLAB-installed functions. This means that if you use a MATLAB-installed function that was introduced in a MATLAB release after the one you are using, it is not reported by this check. You can use checkBuiltinFunctionCompatibility for that. For example if you set the Release parameter to R2020b and you are using R2017b. Conversely, if you use a MATLAB-installed function that was introduced in a MATLAB release after the one you have configured under Release, but that is known in the MATLAB release you are using, the function call will be reported. This is because the function is not supported in the configured MATLAB release, so it is also not Coder-compatible. For example, you set the Release parameter to R2017b and you are using R2020b to run the check.
Exemption tag: %@ok<CCFCN>
3.7.14 checkCommandSyntax
Checks if command syntax statements are used in the code. Readability and maintanability of the code decreases by the use of command syntax statements.
Here an example, avoid
Instead use
Configurable parameter
-
FixWithDoubleQuotes (boolean): Set to true to make the auto-fix option fix the violations with double quotes. If set to false, single quotes are used by the auto-fix. The default value for this parameter is true.
This check has an
auto-fixer. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. You can use the
Fix on this line button to apply the fix to the violations in an individual block of code. The auto-fixer adds quotes and brackets around the input arguments. For more information, see Section
3.11↓.
Exemption tag: %@ok<COSYN>
3.7.15 checkConstantDefinitionAtTop
Checks whether all constants are defined at the top of the function or script. Constant definitions are allowed to come before or after persistent and global declarations. Similar, constant definitions are allowed to come before or after import statements. Starting in MATLAB R2019b, the arguments block is available. Since no code can come before this block, all constant definitions will automatically come after it. For this check, a variable is considered to be a constant if it meets all of the following criteria:
-
The value is assigned once. Also no elements of the variable are allowed to be altered.
-
The value of the variable does not depend on function calls, including most MATLAB-installed functions. The only MATLAB-installed functions that can be used after which the variable may still be considered a constant are: pi, eps, sqrt, and factorial.
-
The value does not depend on other variables.
-
No dot notation is used to assign the variable. For example, struct field assignments will not be considered constants.
Aside from numbers and the MATLAB-installed functions listed above, several operators and constructs can be used in a variable declaration and it can still be considered a constant:
-
The expression for assigning the value can contain zero or more of the following operators: ^, :, *, /, + and -.
-
The expression can also be a row or column vector and use the transpose operator (’).
-
It can contain strings or character vectors (single and double quotes).
Here are some examples of what are considered constants by Code Checker for MATLAB:
a = 100;
b = 1 + 3;
c = 1.3e-9;
d = sqrt(2)/2;
e = pi^2;
f = 3 : 2 : 11;
g = "Test";
h = [3, 5, 10]’;
The following variable declarations are not considered constants by Code Checker for MATLAB:
k(3) = 5;
l = 100; % The value changes on the next line.
l = 200;
m = v + 1; % Where v is not seen as a constant.
n.field = 10;
p = cumsum([3, 5, 8]);
Exemption tag: %@ok<CNDAT>
3.7.16 checkContiguousStructFieldDefinitions
Checks whether for every struct, the fields are defined in a single, contiguous block of code. For this check, a single, contiguous block of code is defined as a block of code without empty lines in it. For example:
s.a = 2;
s.b = 3;
s.c = 100; % Separate block of code, so will be reported.
Additionally, this reports cases where the struct is used before all fields are added, even when it is a contiguous block of code. This only holds when the struct is used as an input to an assignment or function call in its entirety. The individual fields of the struct are allowed to be used before all fields are added. For example:
s.a = 2;
s.b = 3;
myCustomFcn(s);
s.c = 100; % The same code block, but the struct has already been used. This will be reported.
Conversely, the following will not result in a violation being reported by this check:
s.a = 2;
s.b = 3;
myCustomFcn(s.b, s.a);
s.c = 100; % The struct fields are used, but that is fine. No violation to report.
Some remarks about this check:
-
Addition of fields to nested structs will not be reported.
-
Addition of fields using dynamic field names is ignored by this check. This can affect the outcome of the check in two ways:
str = ’myFieldName’;
s.a = 2;
s.(str) = 3;
s.myFieldName = 100; % Even though the field already exists, it is still reported as a violation because it was added dynamically.
str = ’myFieldName’;
s.a = 2;
s.b = 3;
s.(str) = 100; % Even though the field does not exist yet, it will not be reported as a violation because it is a dynamic field assignment.
-
This check supports structs being defined as in the examples as well as those defined using the MATLAB-installed struct function.
-
This check is scoped per function. That means that if the input of your function is a struct, no violation is reported when a new field is added to it in the function.
-
When a new field is added in multiple conditional statements (for example in an if and else), it will only be reported once.
Exemption tag: %@ok<CSTFD>
3.7.17 checkCopyrightNotice
Checks if a specific copyright notice is found in the checked files. A copyright notice can be used as a deterrent against copyright infringement. There are a few configurable parameters for this check. If a copyright notice is lengthy, it may be split across multiple lines in the checked file(s). This is supported by this check. It is required to have your copyright notice on a separate line, so without any code on it.
Configurable parameters
-
Notice (string): The copyright notice that must be included in the files. In order to facilitate checking for a copyright notice of different years, use ’#YEAR#’ in the configuration parameter to indicate any year in this century. This will match copyright notices containing a year such as ’2011-2018’, ’2019’, ’2001 - 2008’. In the configuration file, define the copyright notice on a single line, without line breaks or ’%’ characters to indicate a comment. For example, a notice defined as ’Copyright #YEAR# My Company. All rights reserved.’ will pass this check if your checked file contains ’%% Copyright 2016-2019 My Company. All rights reserved.’.
-
Location (list): Indicate the expected location of the copyright notice. May be one of the following:
-
Top: Place the copyright notice at the top of the file, even before any function or classdef headers.
-
BeforeMainCode: Place the copyright notice right after the function or classdef header, but before other code. If the checked file is a script, the copyright notice is searched for at the top of the file.
-
Bottom: Place the copyright notice at the bottom of the file, after all code (also after local functions).
-
Any: All three locations described before are allowed.
This check has an auto-fixer. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix for this file button fixes the violation for one file.
Exemption tag: %@ok<COPYR>
3.7.18 checkDuplicateAttributes
Checks classdef files and reports any
methods or
properties blocks with duplicate attribute values. Decrease the number of
methods and
properties blocks by combining blocks that have identical attribute values into one. This check considers setting an attribute to its default value equal to omitting the attribute. See what the default values for all attributes are in the
MathWorks documentation. Keep the following in mind for this check:
-
The following sets of attributes are considered equal: (Hidden = true), (Hidden = 1) and (Hidden)
-
The order of attributes is ignored, so these are considered equal: (Hidden, Constant, Access = private) and (Constant, Access = private, Hidden)
-
An empty list of classes that can access the properties or methods is equal to setting private access: (Access = {}) equals (Access = private)
-
Because setting an attribute to its default value is considered equal to omitting the attributes, these are considered equal: (Access = protected, Constant = false, Transient = false) and (Access = protected)
Exemption tag: %@ok<DUPAT>
3.7.19 checkDynamicFields
Reports use of any dynamic struct field names and property names. Aside from personal preferences regarding this construct, this check is especially useful when the code must be MATLAB Coder-compatible (generating C/C++ code from your MATLAB code). This is because dynamic struct field and property names are not supported by the MATLAB Coder. Some examples of what will be reported by this check are (where the variable and name can be a struct and fieldname, or an object and property name):
s.(theField) = 12;
s.x.(otherField) = 10;
a = s.(b + "cd");
c = s.([’test’, ’cat’])
Exemption tag: %@ok<DYNFI>
3.7.20 checkEditorWarnings
Checks if any warning messages are shown to the user in the MATLAB editor. With this check, the user does not need to open a file to see the editor warnings. Warning messages that are suppressed in the MATLAB editor are ignored by this check.
Configurable parameters
-
MlintSettings (string): Choose what settings to use when checking for editor warnings. Options are:
-
Local (default): Use the currently active local settings. This means that the editor warnings as shown in the MATLAB editor will be reported. For more information on changing these settings locally, see this page.
-
Coder-compatibility: Use settings related to coder-compatibility when checking for editor warnings.
-
Factory: Use the factory default settings when checking for editor warnings as shipped with MATLAB.
-
FromFile: Apply changes to the factory settings as defined in a txt-file whose location is given with the SettingsLocation parameter of this check. For more information on creating such a file, see this documentation.
-
SettingsLocation (string): This parameter is only used if the MlintSettings parameter is set to FromFile. It specifies where the settings file that must be used for checking for editor warnings, is located. The file must have extension .txt. It can be an absolute path. If it is not an absolute path, the file is expected to be on the MATLAB path. Keep possible namespaces in mind. The file must be findable using MATLAB-installed function which. If the file is not found this way, it is searched for in the currently active configuration folder (which does not have to be on the MATLAB path). For more information on the manipulation of the configuration folder, see 7↓.
-
MessageIDs(list): Define a list of message IDs to warn for, an empty list or ’all’ reports all warning messages found. For example, the message ID ’AGROW’ reports violations related to: The variable <name> appears to change size on everly loop iteration. Consider preallocating for speed.
Note that this check can be configured multiple times, but the warning messages are obtained once. Which means that only one combination of the parameters ’MlintSettings’ and ’SettingsLocation’ can be used. Therefore it is necessary to configure those two parameter identical for all configuration of this check. If this is not the case when editing a configuration in the Configuration Editor, a dialog will pop up and you will get notified about non-identical parameter values.
Exemption tag: %@ok<EDWRN>
3.7.21 checkExpressionAlignment
Reports code blocks with expressions that are not properly aligned. In order to make your code more readable, consider aligning equals signs of the assignment expressions in a code block. This check reports contiguous blocks of assignments that do not have their equals signs aligned. Any non-assignment line (includes empty lines) indicates the end of a contiguous block of assignments. Some examples that will be reported are:
a = 12;
foobar = 101;
b = 1 ...
+ 3.1415 ^ 2;
eggs = 3;
more = ’test’;
These examples after fixing will look as follows:
a = 12;
foobar = 101;
b = 1 ...
+ 3.1415 ^ 2;
eggs = 3;
more = ’test’;
Here are some examples of pieces of code that will not be reported by this check.
a = 12;
foobar = 101;
b = 1 ...
+ 3.1415 ^ 2;
someFunctionCall(b);
eggs = 3;
Alignment is checked based on the number of characters before the equals signs. A tab is treated as a single character, which means that equals signs may seem aligned, but a violation is reported anyway because for a different setting of the tab size, they are not aligned. Sets of method declarations, properties blocks and arguments blocks will not be reported by this check.
This check has an
auto-fixer. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. You can use the
Fix on this line button to apply the fix to the violations in an individual block of code. The auto-fixer insert spaces, not tabs. For more information, see Section
3.11↓.
Exemption tag: %@ok<EXPAL>
3.7.22 checkFollowedBySpace
Checks if commas, semicolons and keywords are followed by a space. Per default, this does not report commas, semicolons and keywords that are only followed by white space until the end of the line. This check also does not report any violations that are found in strings or comments. Enable this check to help improve readability of the code.
All MATLAB keywords in alphabetical order are: arguments (from R2019b), break, case, catch, classdef, continue, else, elseif, end, for, function, global, if, otherwise, parfor, persistent, return, spmd, switch, try and while.
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one indivual line. For more information, see Section
3.11↓. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Exemption tag: %@ok<FOLSP>
3.7.23 checkFunctionCallExcessInputs
Check that functions are not called with more inputs than expected. If a function is called with more input arguments than expected, it will result in an error when the code is run. Calls to MATLAB-shipped and calls to mex-functions are ignored by this check. In case the function contains a Repeating arguments block or name-value arguments no violation will be reported.
Exemption tag: %@ok<FCTMI>
3.7.24 checkFunctionIndented
Used to check whether or not functions are indented. Rules may specify that the contents of every function must be indented or that they should not be. The following rules apply to this check:
-
A line of code is considered indented if it has at least IndentationLength whitespace characters at the start, with IndentationLength a parameter value.
-
Comments are ignored during this check.
-
A function block is only considered indented if all of its code is indented.
-
A function block is considered non-indented if at least one line of code has zero indentation.
Configurable parameters
-
DoIndent (boolean): Set to 1 to require a function block to be indented. Set to false if function blocks should not be indented.
-
IgnoreTabs (boolean): Set to 1 to ignore violations related to tabs, the check does not result in unnecessary violations when using another computer with a different MATLAB preference ’EditorSpacesPerTab’. The default value for this parameter is false.
-
IndentationLength (double): The minimum indentation length. If a function block must be indented, code must at least be indented by this amount of whitespace characters. Note: this value is ignored when DoIndent is set to 0, because in that case, the code should not be indented at all. The value must lie between 1 and 8.
Exemption tag: %@ok<CFIND>
3.7.25 checkFunctionPrefix
Checks if the names of local functions (also referred to as subfunctions) and nested functions are prefixed with specified prefixes. By prefixing these functions, calls to local or nested functions can easily be distinguished from other function calls. This check ensures that the prefixes are actually used as prefixes: at the start of the name and followed by at least one character.
-
LocalFunctionPrefix (list): A list of prefixes for local functions that are allowed to be used. If the list is empty, local functions do not have to be prefixed with anything.
-
NestedFunctionPrefix (list): A list of prefixes for nested functions that are allowed to be used. If the list is empty, nested functions do not have to be prefixed with anything.
Exemption tag: %@ok<FCNPF>
3.7.26 checkGetterAndSetter
Checks if methods such as get.MyProperty() and set.MyProperty() have been declared. The rationale behind this check is that nothing should happen when you set or get a property when it is used directly to make sure that the code stays readable and does not produce any unexpected side effects. If it is necessary that actions are performed when getting or setting a property, make the property private and implement explicit getters and setters (for example getMyProperty() and setMyProperty()).
Exemption tag: %@ok<GETST>
3.7.27 checkGlobalUsed
Checks if the keyword global is used. Use of this keyword is often discouraged (not in MATLAB specifically) because (among many other reasons) it becomes very difficult to determine which functions access these variables. This keyword has its own check because its priority is often higher than that of the keywords and functions listed under checkAvoidFunction.
Exemption tag: %@ok<GLOBU>
3.7.28 checkJavaUsed
Checks if the code uses Java. It may be that one wants to be independent of Java, for example because Java packages and subpackages will not be available in MATLAB in a future release.
Exemption tag: %@ok<JAVUS>
Checks if every if has a matching else section. Defining an else section for every if improves readability by showing more clearly what it means when the if (and possible elseif’s) condition are not satisfied.
Exemption tag: %@ok<IFELS>
Configurable parameters
-
AllowIfWithoutElse (boolean): Set to true to allow an if, that does not have an elseif section, without a matching else section. The default value for this parameter is false.
Checks if constructs such as if true are used. Using this type of if-statements reduces readability and can generally be left out. The full list of constructs of this type that is checked is: if true, if false, if 1 and if 0. Note that in some of these cases, MATLAB’s Code Analyzer will display a warning message already.
Exemption tag: %@ok<IFTRU>
3.7.31 checkIndentationLength
Check if all indented lines have an indentation length divisible by parameter indentation length, except for white lines. Consistent indentation increases the readability of the code. This check may not work as expected when tabs do not insert whitespace, but tab characters.
Configurable parameter
-
IndentationLength (double): The indentation length of indented code should be divisible by the parameter IndentationLength. The default value for this parameter is 4 and it can be changed to anywhere between 1 and 12.
Exemption tag: %@ok<CINLE>
3.7.32 checkLineLength
Checks if the length of a line exceeds the maximum line length according to the coding standards, for readability it is advisable to have a maximum on the line length. Check includes comments and whitespaces.
-
MaxLineLength (double): Lines that are longer than this value are reported. The default value for this parameter is 120 and it can be changed to anywhere between 50 and 200.
Exemption tag: %@ok<LILEN>
3.7.33 checkLogicalOperator
Checks for usage of logical operators && and || in logical expression. The short-circuit operators && and || only work on scalars and are therefore not useful for general logical expressions. Use elementwise logical operators & and | instead. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Exemption tag: %@ok<LOGOP>
3.7.34 checkLoopIteratorNaming
Checks if iterator variables are prefixed with i, j, k etc. Depending on the parameters for variable casing, this can mean that iterator variables can be of the form iRow, jTest (lower/upper Camel casing), i_row, j_test (Snake casing), iROW, jTEST (screaming Snake casing) or or irow, jtest (lower casing). When enabled, this check fails if:
-
The iterator variable name does not start with i, j, ..., z.
-
The first character is not followed by an upper case character (lower/upper Camel/screaming Snake casing), a lower case character (lower casing) or an underscore followed by a lower case character (Snake casing).
Configurable parameters
-
SubsequentLettering(boolean): True if, in nested for-loops, the starting letters of the iterator names shall be subsequent letters in the alphabet.
-
MinimumLength(double): The minimum length for iterator variable names, the name should be descriptive. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 20.
-
UseVariableCasing(boolean): Set to 1 to use the casing parameters for variable casing. If set to 0, iterator variable names can be of the forms lower/upper Camel casing, Snake casing, screaming Snake casing or lower casing.
By maintaining a convention on iterator variables, these can easily be distinguished within the code.
Exemption tag: %@ok<IDXNA>
3.7.35 checkMagicNumber
Reports use of so-called magic numbers or unnamed numerical constants in your code. These are numbers used directly in the code without being assigned to a variable first. For example, replace
x = 9.81 * t;
with
g = 9.81; % Gravity constant.
x = g * t;
Using magic numbers in your code can degrade readability and the author’s intent for them may not be apparent. There are some situations that will not be reported. For example, comparing the output of nargin or exist to a number that would normally be reported. Aside from these exceptions, this check’s strictness can be configured using the parameters described below. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Configurable parameters
Exemption tag: %@ok<MAGNR>
3.7.36 checkMethodAccessPermissions
Checks classdef files to see if any methods use different access permissions than their superclass (if any). If this is the case, the class cannot be instantiated and an error will be thrown indicating this problem. This checks method declarations as well as implementations thereof in the classdef file.
Limitations
If the classdef file could not be analyzed due to another problem (for example, invalid property definitions), no violation is reported by this check.
Exemption tag: %@ok<METAP>
3.7.37 checkMethodsInClassdef
Check if all methods that are declared in a classdef file are also implemented, and that the declaration is the same as the implementation. Also check that the declaration is the same as the implementation (i.e. do not declare varargin but have a method with "(x,y,x)" input arguments). Check that all methods that have an implementation in a seperate file are also declared.
Configurable parameters
-
AllowDifferentInputOutputNames (boolean): Set to true to have Code Checker for MATLAB allow for differences in method input and output names between method declaration and implementation. By default, this parameter is set to false.
-
AllowVararginout(boolean): Set to true to have Code Checker for MATLAB allow the use of varargin/varargout in method input and output declaration and implementation.
Exemption tag: %@ok<MDAMI>
3.7.38 checkMissingComma
Check if any rows lack properly placed commas to separate the elements. Some examples that will be reported as violations by this check and their accepted equivalents:
% Violations:
txt = [’test ’ var ’ text.’];
values = [1 1 2 3 5 8 13];
myCells = {obj1 ,obj2};
multi = [’The multi-’ ...
’line char array.’];
% Accepted equivalents:
txt = [’test ’, var ’, text.’];
values = [1, 1, 2, 3, 5, 8, 13];
myCells = {obj1, obj2};
multi = [’The multi-’, ...
’line char array.’];
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one individual line. For more information, see Section
3.11↓.
When multiple function outputs are not separated by commas, it can reported by
checkEditorWarnings↑. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Exemption tag: %@ok<MCOMM>
3.7.39 checkMissingSemicolon
Reports lines of code that could result in output to the command window because they are not terminated with a semicolon. Use this check to determine the part of your code that produces unwanted or unexpected output. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Configurable parameters
-
ReportAll (boolean): Set to true to have Code Checker for MATLAB report all lines that could result in output to the command window due to not being terminated with a semicolon. For example, this includes calls to the error function. This setting can be used when your coding standards require that all lines of code are terminated with semicolons. When set to false, this check only reports lines that have a MATLAB warning about missing semicolons (lines that will definitely generate output to the command window when executed). By default, this parameter is set to false.
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one individual line. For more information, see Section
3.11↓.
Exemption tag: %@ok<MSEMC>
3.7.40 checkMixedTypesExpression
Checks expressions and conditions to see if operands or operators of logical and numerical types were mixed. Mixing operand types in an expression or condition decreases code readability and robustness. Some examples of expressions that will be reported by this check are:
a = 8.9 || 9.1; % Numbers and logical operator ||.
b = isempty(a) * 3; % MATLAB-installed function ’isempty’ and the multiplication operator.
c = a * b & a > b; % Multiplication and the logical operator &.
d = a / ~c; % Division and the ’not’ operator.
Since Code Checker for MATLAB cannot reliably determine a variable’s type, this check does not use such information. Only information known at the expression or condition itself will be used. Aside from the operators themselves, a non-exhaustive list of MATLAB-installed functions (including isempty as shown in the example) is used to determine the operand types.
Exemption tag: %@ok<MIXOT>
3.7.41 checkNameIsShadowing
Checks for all variables and functions in the file(s) whether they shadow any existing functionality. For example: if a variable named pi is defined, you will no longer have access to the actual value of π within that file. This can cause unexpected and undesired behaviour. Variables and functions are reported if they have the same name as one or more of the following:
-
MATLAB-installed functions. As described here, certain method names are supposed to overload MATLAB-installed functions. When used as the right type of method, these are ignored by this check, regardless of whether or not they are configured as exceptions.
-
Classes
-
Packages
-
MATLAB executable files (MEX): .mexw32, .mexw64, .mexa64, .mexmaci64
-
Simulink files: .mdl, .slx. Detecting the shadowing of a Simulink file requires a Simulink license.
-
Other MATLAB files: .m, .mlx, .mlapp, .p
Configurable parameters
-
Exceptions (list): A list of names that do not need to be checked for shadowing. Add names to this list if you want to shadow certain files/functions or if you do not mind shadowing specific files. Suggestions for exceptions include input/output-related functions: nargin, nargout, varargin and varargout.
Exemption tag: %@ok<NSHAD>
3.7.42 checkNameLength
Checks if the length of function and/or variable names are within the allowed minimum and maximum length according to the coding standards. Limiting the lenght of function and variable names increases the readability of the code.
Configurable parameters
-
MinFuncNameLength (double): The minimum length for function names. The default value for this parameter is 3 and it can be changed to anywhere between 5 and 63.
-
MaxFuncNameLength (double): The maximum length for function names. The default value for this parameter is 30 and it can be changed to anywhere between 5 and 63.
-
MinVarNameLength (double): The minimum length for variable names. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 63.
-
MaxVarNameLength (double): The maximum length for variable names. The default value for this parameter is 25 and it can be changed to anywhere between 1 and 63.
Exemption tag: %@ok<NALEN>
3.7.43 checkNegatedBoolean
Checks if there are no variables that have negated boolean names such as notValid, is_not_ok. Using such variables in conditional expressions can be confusing and difficult to read and therefore, this check may be enabled. Based on the casing used for variables, this reports variables with names that:
-
Lower Camel casing: Starts with not followed by anything other than a lower case character, or it contains Not followed by anything other than a lower case character.
-
Upper Camel casing: Contains Not followed by anything other than a lower case character.
-
Snake casing: Starts with not_, it contains _not_, or it ends with _not.
By using these settings instead of just looking for not, names such as notation and myNotifier will not be reported as fails of this check.
Configurable parameters
-
VariableCasing (string): This check automatically uses the Casing setting from the checkVariableCasing check to determine how to detect negated boolean variable names. This means that the check on variable casing must be enabled if this check is enabled.
Exemption tag: %@ok<NEGBO>
3.7.44 checkNestedFunction
Checks if there are any nested functions used. Using nested functions is often discouraged because it can degrade code readability.
Exemption tag: %@ok<CNSTF>
3.7.45 checkNestingDepth
Check on the nesting depth of blocks. Limiting the nesting depth of blocks increases the readability of the code.
Configurable parameter
-
MaxNestDepth (double): The maximum nesting depth of a block. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 10.
Exemption tag: %@ok<NSTDP>
3.7.46 checkNoInputArg
Checks if all function calls without input arguments have empty parentheses. Most importantly, using empty parentheses instead of leaving them out helps to distinguish between accessing an object’s properties and using it’s methods. Additionally, it clearly shows where functions are called. In order to prevent copious amounts of fails to this check, a number of MATLAB-installed functions will be ignored when called with no input arguments and with no empty parentheses. These are: false, true, pi, eps, nargin, nargout, mfilename, pwd, cd, Inf, NaN, clc, clear, rand, randn, i, j, filesep, tempname, tempdir, drawnow, NaT, date and now.
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one indivual line. For more information, see Section
3.11↓.
Configurable parameters
-
Exceptions (list): A list of additional functions that do not require empty parentheses when called with no input arguments.
-
IgnoreBuilt-ins (boolean): Set to true to have this check ignore MATLAB-installed functions and toolbox functions. If set to true, function names in the Exceptions list are still taken into account.
Limitations
-
Does not report calls to methods that have no input arguments besides an object and no empty parentheses. For example params = obj.getParameters will not be reported by this check.
Exemption tag: %@ok<INPAR>
3.7.47 checkNumberOfInputsOutputsFunction
Checks if there are any functions with too many inputs or outputs. For readability of the code it is advisable to limit the number of input and output parameters of a function. It is recommended to group related parameters into structures.
Configurable parameters
-
MaxNumberOfInputs (double): The maximum allowed number of input parameters of a function. The default value for this parameter is 5 and it can be changed to anywhere between 1 and 10.
-
MaxNumberOfOutputs (double): The maximum allowed number of output parameters of a function. The default value for this parameter is 5 and it can be changed to anywhere between 1 and 10.
-
ExemptConstructor (boolean): Set to true to have this check exempts constructors. The default value for this parameter is false.
Exemption tag: %@ok<NINOF>
3.7.48 checkNumberOfOutputsConstructor
Checks the number of outputs of a constructor, it is often desired to have only one output: an object of the class.
Exemption tag: %@ok<NOOCS>
3.7.49 checkOneStatementPerLine
Checks if there is at most one statement per line. For readability, it is advisable to have at most one statement per line.
Configurable parameters
-
AllowMultipleGlobalVars (boolean): Whether or not multiple global variables are allowed to be defined on the same line. The default value is true.
-
AllowMultiplePersistentVars (boolean): Whether or not multiple persistent variables are allowed to be defined on the same line. The default value is true.
Exemption tag: %@ok<OSTPL>
3.7.50 checkOperatorsLineContinuation
Checks if multi-line statements are split before or after binary operators. For example, consider the difference between the following two statements:
isValid = testsPass ...
&& validationPassed;
isValid = testsPass && ...
validationPassed;
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one individual line. For more information, see Section
3.11↓.
Configurable parameters
-
OperatorPosition (string): Desired position of binary operators in multi-line statements. Can be StartOfLine (top example) or EndOfLine (bottom example). The default is StartOfLine.
-
CheckAssignmentEqualsSigns(boolean): Whether or not equals signs used in assignments need to be checked as well. The default is false.
Exemption tag: %@ok<OPLCO>
3.7.51 checkParenthesesLogicalOperators
This check reports any statements in which insufficient parentheses are used to clarify the precendence of logical operators. Any statement where the operator precedence affects the outcome must use sufficient parentheses. For example:
x = a && b || c; shall become x = (a && b) || c; or x = a && (b || c);
When only one type of logical operator is used, operator precedence is irrelevant and no parentheses are required for this check. For example: x = a && b && c;
Configurable parameters
-
RequireParenthesesAroundCondition (boolean): Set to true to require parentheses around if and elseif-statements, even though these are not required to clarify operator precedence. For example: if a && b should become if (a && b).
Exemption tag: %@ok<PARLO>
3.7.52 checkParenthesesMathematicalOperators
Checks if all statements with mixed mathematical operators use sufficient parentheses to clarify operator precedence. The mathematical operators that are checked are: +, -, /, *, and .*. As an exception, + and - are allowed to be used successively without requiring parentheses for clarifying operator precedence because the order in which the operators are treated does not matter. In the HTML report at most one violation of the same type per line of code will be shown for this check. Some examples of code that will be reported by this check are:
x = 6 * 2 + 1;
y = 1 / 2 * 3;
z = 2 * pi + 2;
Some examples of code that will not be reported by this check are:
a = 6 * 2 * 1;
y = 1 + 2 - 3 + 5;
z = (2 * 3) + (5 * 2);
Exemption tag: %@ok<PARMO>
3.7.53 checkPersistentUsed
Checks if the keyword persistent is used. Use of this keyword is often discouraged (not in MATLAB specifically) because (among many other reasons) it becomes very difficult to determine which functions access these variables. This keyword has its own check because its priority is often higher than that of the keywords and functions listed under checkAvoidFunction.
Exemption tag: %@ok<PERSU>
3.7.54 checkPropertiesBeforeMethods
Checks if all properties blocks are before all method blocks in classdef files. For readability, it is advisable to have all properties blocks before the method blocks in classdef files.
Exemption tag: %@ok<PBBMB>
3.7.55 checkPropertyClassRedundancy
Checks if there are properties that contain the name of the class. For readability, it is advisable to not have redundancy in a property name.
Exemption tag: %@ok<PRCLR>
3.7.56 checkReuseIteratorVariableName
Checks if iterator variable names are reused as iterator variable within a function. Not reusing iterator variable names prevents renaming all iterators when only the one for a specific loop must be renamed. Not reusing iterator variable names also improves readability.
If both this check and
3.7.34↑ are enabled, possible violation messages contain a note that the user should be aware of it.
Exemption tag: %@ok<RUIVN>
3.7.57 checkScriptFileUsed
Checks if there is a script file used. Scripts are not always desired, use functions and classes instead.
Exemption tag: %@ok<SCRFU>
3.7.58 checkSecurityWebOptions
Checks if the weboptions function is used securely:
-
The CertificateFilename property value shall not be empty. Using an empty certificate file name disables certificate validation.
-
The Username and Password properties shall not be directly set using strings or character arrays. Instead, their values shall be obtained externally.
Exemption tag: %@ok<SECWO>
3.7.59 checkSecurityXml
Checks if XML files are accessed securely. Insecure deserialization results in code execution. Specifically for XML this can result in DoS (Denial of Service) attacks when allowing the use of DOCTYPE declarations. This is well documented
here.
Since MATLAB R2019b, you can prevent reading XML files that contain DOCTYPE declarations by setting the ’AllowDoctype’ name-value pair of the xmlread function to false. This check will report a violation if the xmlread function is used without setting AllowDocType to false. For more information, see the xmlread reference page.
Since MATLAB R2021a, you can read XML files using the matlab.io.xml.dom.Parser class. By default, the AllowDoctype property of the parser’s Configuration property is set to false. Therefore, this check reports a violation if the property is explicitly set to true, and not if the property is not set at all.
Exemption tag: %@ok<SCXML>
3.7.60 checkShellEscape
Checks if the shell escape function is used in the code. An exclamation point (!) indicates that the rest of the line is a command to the operating system. This is called a shell escape. As an alternative, you can use the MATLAB-installed function system. If your coding standards dictate that no system calls should be used, configure checkAvoidFunctions such that use of the system function is reported in addition to the shell escape function.
Exemption tag: %@ok<SHESC>
3.7.61 checkStringDataType
Checks if the string data type is used in the code. The string data type was introduced in MATLAB R2016b and the double quote notation was introduced in MATLAB R2017a. For backwards compatibility purposes, it can therefore be desired not to use this data type. It may also be for consistency reasons that you want to check if this data type is used. This check reports a violation when the double quote notation is used to indicate a string or when the MATLAB-installed string() or strings() function is used. When multiple strings are defined on a single line using double quotes, only the first violation is reported. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Note that this check only reports the cases described above. This mostly means that MATLAB-installed functions that can output a string are not reported as violations. For example: data = readtable(’test.csv’, ’TextType’, ’string’); will output a table containing strings, but no violation is reported.
Exemption tag: %@ok<STRDT>
3.7.62 checkStructFieldNames
Checks whether any structure field names contain the name of the struct. For example: sensor.SensorWeight. This is a case insensitive check. This check checks fields that are defined in the following manner: test.TestLength = 10;. Additionally, field names defined using the struct() function like test = struct(’TestLength’, 10); are also checked.
Limitations
Dynamically assigned field names are not checked by this check because the field names cannot be collected. Therefore, structures defined as follows will not result in violating this check:
fieldNames = {’my_field’, ’my_2nd_field’};
myStruct = struct(fieldNames{1}, [], fieldNames{2}, []);
str = ’TEST’;
myStruct.(str) = [];
An additional limitation related to this check is given in Chapter
9↓.
Exemption tag: %@ok<SFNAM>
3.7.63 checkSubFunction
Checks if there are any sub functions used. Using sub functions is often discouraged because it can degrade code readability, testability and re-use. Use seperate function files instead of sub functions.
Exemption tag: %@ok<CSUBF>
3.7.64 checkSuperclassPropertyImplementation
Checks classdef files to see if it implements any superclass properties (if any). If this is the case, the class cannot be instantiated and an error will be thrown indicating this problem.
Limitations
If the classdef file could not be analyzed due to another problem, it could be that no violation is reported by this check, depending on the nature of the other problem.
Exemption tag: %@ok<SUPPI>
3.7.65 checkSuppressAll
Checks if there are any MATLAB Code Analyzer messages being suppressed throughout the file. Code Analyzer messages should generally be prevented. If they are not prevented, they should be suppressed and have an accompanying comment stating the reason for suppression (not checked by checkSuppressAll). It is advisable not to do this throughout an entire file because the same warning may be helpful elsewhere.
Exemption tag: %@ok<SUPAL>
3.7.66 checkSurrBySpaces
Checks if certain operators are surrounded by spaces. Surrounding for example ’=’ by spaces makes the code more readable. This check excludes strings and comments.
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one indivual line. For more information, see Section
3.11↓. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Configurable parameters
-
Operators (list): List of operators that must be surrounded by spaces. Allowed values are: =, :, ^, .^, ==, <=, >=, ~=, >, <, &, &&, |, ||, +, -, *, .*, /, ./ and .\. By default, the value of this parameter equals the list of allowed values.
-
When you configure the check to look for :, code will not be reported as a violation when it is used for indexing. For example x(:, 1) or y{:} will not result in a violation, but 1:10 will.
-
If you configure the check to look for -, the check will only report violations if it is used as a subtraction, not to negate a value. So -5 * 2 will not be reported and 10-2 will.
-
SurroundNameValueEqualsSigns (boolean): Whether or not equals signs in name-value pairs when using the Name=value syntax should be surrounded by spaces (available since MATLAB R2021a). For example, when set to true, the following will be reported: plot(x, y, LineWidth=2) and when set to false, this will be reported as a violation: plot(x, y, LineWidth = 2). The default value is false. The behaviour of this check regarding equals signs in name-value pairs is applied regardless of the value of the Operators parameter. When you are not using MATLAB R2021a or newer, this parameter is ignored.
Exemption tag: %@ok<SURSP>
3.7.67 checkSwitchOtherwise
Checks if every switch statement has a matching otherwise section. Defining an otherwise section improves readability by clearly showing what happens when none of the case’s are triggered. It also allows for defining error messages if required.
Exemption tag: %@ok<SWOTH>
3.7.68 checkTabCharacterUsed
Checks if tab characters are used, since the length of a tab can vary it is therefore advised to use spaces instead. Using
"\t" or
char(9) is not reported instead. In case of multiple violations per line of code, only one violation per line is shown in the report. This check has an
auto-fixer. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one individual line. The auto-fixer inserts spaces. For more information, see Section
3.11↓. In the HTML report at most one violation of the same type per line of code will be shown for this check.
Exemption tag: %@ok<TABCU>
3.7.69 checkTestSuffix
Checks if the configured suffix is reserved for unit test files. Unit test files can be classdefs, functions or scripts. What is considered to be a unit test file by Code Checker for MATLAB is defined as follows:
-
Classdef files: A method is defined within a methods block that has the Test attribute. If the class meta information could not be obtained (for example because the calculation of a default value of a property triggered an error), the file is not considered a test file.
-
Function files:
-
The MATLAB-shipped functiontests function is called in the main function of the file.
-
The file name starts or ends with test (case-insensitive).
-
Scripts: The file name starts or ends with test (case-insensitive).
This check reports files in two situations:
-
If the file is considered a test file but it is not suffixed with the configured suffix.
-
If the file is not considered a test file but it is suffixed with the configured suffix.
Configurable parameters
-
Suffix (string): The suffix to reserve for unit test files.
Exemption tag: %@ok<TSTSF>
3.7.70 checkTryExceptionHandling
Run this check to check if all try blocks are only used for exception handling. Although not recommended, try statements could also be used to suppress errors or to express a simple condition. checkTryExceptionHandling checks the following for every try:
-
Is there a catch block with at least one line of executable code?
-
Is an exception object assigned or created in the catch?
-
Assigned: catch ME
-
Created: ME = MException(errorID, msg);
-
Is at least one of the list of exception handling MATLAB-installed functions or keywords used in the catch?
This does not check if points 2 and 3 hold for all execution paths within the catch, so if you use an if-else within the catch and only call an exception handling function in one of the two, it is not reported by this check.
Configurable parameters
-
RequireExceptionObject (boolean): When set to true (default), perform check 2. When set to false, do not require an exception object to be assigned or created in the catch.
-
ExceptionHandlingFunctions (list): List of functions or MATLAB keywords (return etc.), at least one of which must be called within every catch. The default list is error, throw, rethrow, throwAsCaller. Other suggestions are: errordlg, warning, return or some user-defined exception handling function.
Exemption tag: %@ok<TRYEH>
3.7.71 checkTryUsed
Checks if MATLAB’s try - catch construct is used. Using this construct is often discouraged because it can degrade code readability. It can be unclear what is expected to go wrong within the try and it is therefore generally advised to write code around what could go wrong.
Exemption tag: %@ok<TRYUS>
3.7.72 checkUseIteratorVariableNameOutsideLoop
Checks if loop iterator variables are used outside the for-loop. Using a loop iterator variable name outside the for-loop might indicate a programming error.
Exemption tag: %@ok<UIVOL>
3.7.73 checkWarningUsed
Checks if warnings are used. Do not throw warnings, if necessary throw errors instead. Using errors instead of warnings improves the robustness of the code. Warnings cannot reliably be caught and handled and therefore often accomplish little. The check ignores calling warning for disabling, enabling, or querying a warning. This means that using for example warning(’off’, ’matlab:my:identifier’); is not reported by this check.
This check also reports cases where a warning state is set using a variable. Consider the following example:
warningState = ’off’;
warning(warningState, ’matlab:my:identifier’);
The statements do not issue a warning when run, but this check reports the second statement.
This check also reports calls to warning when you have shadowed the MATLAB-installed function with a local one..
Exemption tag: %@ok<WARNU>
3.7.74 checkWhiteSpaceEndOfLine
Checks if white space is used at the end of a line. For readability purposes do not use white space at the end of a line, comments are not taken into account, empty lines are ignored.
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one indivual line. For more information, see Section
3.11↓.
Exemption tag: %@ok<WSEOL>
3.7.75 checkZeroBeforeDecimalPoint
Checks if the decimal point in numeric expressions has a zero before it, a zero before the decimal point increases the readability of the code The following example shows what will be reported and what should be used instead:
% Will be reported as a violation:
threshold = .5;
value_x = .1e9;
% Instead use:
threshold = 0.5;
value_x = 0.1e9;
This check has an
auto-fixer as well. Clicking the
Fix all button in the report fixes all violations for this check, clicking the
Fix all in this file button fixes all violations for this check for one file. The
Fix on this line button applies the fix on one indivual line. For more information, see Section
3.11↓.
Exemption tag: %@ok<CZBDP>
3.7.76 Casing checks
Code Checker for MATLAB has several checks on the casing of names of certain aspects in the code. The casing of names can be checked for the following:
-
Variables (checkVariableCasing, exemption tag: %@ok<CVARI>)
-
User-defined functions (checkUserDefinedFunctionCasing1, exemption tag: %@ok<CUDFU>)
-
Structure fields (checkStructFieldCasing2, exemption tag: %@ok<CSFIE>)
-
Methods (checkMethodCasing3, exemption tag: %@ok<CMETH>)
-
Name-value pairs in arguments blocks (checkNameValuePairCasing, exemption tag: %@ok<CNVPC>). The arguments block was introduced in MATLAB R2019b.
-
Classes (checkClassCasing, exemption tag: %@ok<CCLAS>)
-
Class properties (checkPropertyCasing4, exemption tag: %@ok<CPROP>)
-
Packages (checkPackageCasing, exemption tag: %@ok<CPACK>)
-
Events (checkEventCasing, exemption tag: %@ok<CEVEN>)
-
Enumeration members checkEnumMemberCasing, exemption tag: %@ok<CENME>)
1checkUserDefinedFunctionCasing: This only checks the names of user-defined functions that are not methods. The names of methods are checked elsewhere. Furthermore, when this check is used in combination with checkFunctionPrefix, prefixes are subtracted before checking if the functions are cased according to the configured values.
2checkStructFieldCasing: this check suffers from the same limitation as checkStructFieldNaming: casing of dynamically assigned field names will not be checked.
3checkMethodCasing: does not report declarations of methods that are incorrectly cased if their functionality is specified in a separate function file. Additionally, getter and setter methods are ignored in this check, because their names are derived from property names that have a separate check. Constructor names are ignored during this check because they are named after the class. Finally, methods that overload a method of a superclass, are not checked here because those method names are not defined by the checked classdef file. Note, if a superclass has its own superclass(es), this is not taken into account.
There is a separate check for each of these, which means that every casing check can have their own parameter values. The parameters each of the casing checks has, are:
-
Casing (string): Sets the type of casing that needs to be checked. This value can be either ’UpperCamelCasing’, ’lowerCamelCasing’, ’snake_casing’, ’SCREAMING_SNAKE_CASING’ or ’lowercasing’.
-
MaxConsecUpper (double): The allowed maximum number of upper case characters in a row. This value can be increased to allow acronyms in upper case. The value must be between 0 and 50.
-
MaxConsecLower (double): The allowed maximum number of lower case characters in a row. This value can be decreased to be able to detect names that lack upper case characters where needed. The value must be between 0 and 50.
-
AllowNumbers (boolean): Set this to true to allow numbers in the name.
These parameters combined are used to check the casing of names as follows:
-
UpperCamelCasing: One or more repetitions of: between one and MaxConsecUpper upper case characters followed by between one and MaxConsecLower lower case characters. The name is allowed to end with upper case characters. Only letters are allowed. If AllowNumbers is true, any number of numbers is allowed in the name.
-
lowerCamelCasing: Between one and MaxConsecLower lower case characters in a row followed by one or more repetitions of: between one and MaxConsecUpper upper case characters followed by between one and MaxConsecLower lower case characters. The variable name is allowed to end with upper case characters. Only letters are allowed. If AllowNumbers is true, any number of numbers is allowed in the name.
-
snake_casing: Starts with between one and MaxConsecLower lower case characters followed by one or more repetitions of: an underscore followed by between one and MaxConsecLower lower case characters. If AllowNumbers is true, any number of numerical characters is allowed. Note: this does not allow a name to end in an underscore, and it does not allow for multiple consecutive underscores.
-
SCREAMING_SNAKE_CASING: Starts with between one and MaxConsecUpper upper case characters followed by one or more repititions of: an underscore followed by between one and more MaxConsecUpper upper case characters. If AllowNumbers is true, any number of numerical characters is allowed. Note: this does not allow a name to end in an underscore, and it does not allow for multiple consecutive underscores.
-
lowercasing: Can only contain lower case characters (so no underscores) and -optionally- numbers.
Upon a rule violation, the casing checks provide the same information as the other checks do: A path to the checked file, the part of the code violating the coding standards, the scope (if appliccable), and a feedback message.
Constant properties casing
Constant properties may be subject to different casing rules. This is made available with checkNamedConstantCasing. This casing check behaves different from the other casing checks:
-
Constant properties are not required to be cased as specified in the parameters of the check on named constant casing. They are still allowed to be cased like any other property.
-
The check does not have its own results table in the report.
-
When this check is enabled and a constant property does not satisfy the coding standards of regular properties or those of constant properties, the property is listed in the results table of checkPropertyCasing.
3.7.77 Missing checks
If the checks available within Code Checker for MATLAB do not cover something you want to have checked, please contact us at
info@monkeyproofsolutions.nl.