Main Content

MATLAB Code Analyzer Warnings

Syntax Warnings and Property Names

The MATLAB® Code Analyzer helps you optimize your code and avoid syntax errors while you write code. It is useful to understand some of the rules that the Code Analyzer applies in its analysis of class definition code. This understanding helps you avoid situations in which MATLAB allows code that is undesirable.

Variable/Property Name Conflict Warnings

The Code Analyzer warns about the use of variable names in methods that match the names of properties. For example, suppose that a class defines a property called EmployeeName and in this class, there is a method that uses EmployeeName as a variable:

properties
   EmployeeName
end
methods
   function someMethod(obj,n)
      EmployeeName = n;
   end
end

While the previous function is legal MATLAB code, it results in Code Analyzer warnings for two reasons:

  • The value of EmployeeName is never used.

  • EmployeeName is the name of a property that is used as a variable.

If the function someMethod contained the following statement instead:

obj.EmployeeName = n;

The Code Analyzer generates no warnings.

If you change someMethod to:

function EN = someMethod(obj)
   EN = EmployeeName;
end

The Code Analyzer returns only one warning, suggesting that you might actually want to refer to the EmployeeName property.

While this version of someMethod is legal MATLAB code, it is confusing to give a property the same name as a function. Therefore, the Code Analyzer provides a warning suggesting that you might have intended the statement to be:

EN = obj.EmployeeName;

Exception to Variable/Property Name Rule

Suppose that you define a method that returns a value of a property and uses the name of the property for the output variable name. For example:

function EmployeeName = someMethod(obj)
   EmployeeName = obj.EmployeeName;
end

The Code Analyzer does not warn when a variable name is the same as a property name when the variable is:

  • An input or output variable

  • A global or persistent variable

In these particular cases, the Code Analyzer does not warn you that you are using a variable name that is also a property name. Therefore, a coding error like the following:

function EmployeeName = someMethod(obj)
   EmployeeName = EmployeeName; % Forgot to include obj.
end

does not trigger a warning from the Code Analyzer.

Related Topics