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>