Coding style

Rules on how to use language constructs.

Constructors

The following rules apply to introducing new constructors:

  • Constructors should always call the inherited constructor
  • Avoid reintroducing constructors only to fix parameters at a certain value

Case statements

The following rules apply to case statements:

  • If a case statement is intended to cover every option of the selector, be sure to include an else branch which raises an exception indicating an unknown option is detected. Only if the case statement is intended to be sparse the else branch can be left out.

    1 2 3 4 5 6 7 case Value of 1: Result := '1'; 2: Result := '2'; 3: Result := '3'; else raise EUnknownEnumerationValue.Create('Unknown value: ' + TStandardIntegerTextFormat.Decimal.ToText(Value)); end;

Class declarations

The following rules apply to organizing class declarations:

  • Visibility sections are ordered from low visibility to high visibility: private, protected, public and published
  • Always explicitly define a visibility for a section so do not omit the visibility specifier
  • When deriving from TObject, always explicitly define this in the declaration.
  • Within a visibility section declarations are ordered in the following way:

    1. Fields
    2. Constructors
    3. Destructors
    4. Overridden inherited functions
    5. Newly introduced virtual functions
    6. Newly introduced non-virtual functions
    7. Properties
  • If fields or other declarations need special grouping a separate visibility section should be used. At the very minimum class level declarations should be separated from instance level declarations by placing them into separate visibility sections.

    1 2 3 4 5 6 7 8 9 10 11 TTest = class(TObject) public constructor Create(); virtual; destructor Destroy(); override; procedure Test(); public class procedure Initialize(); class procedure Finalize(); end;

Protecting memory and resources

When allocating memory or a resource for the duration of a function, be sure to protect that memory or resource with a try...finally statement:

1 2 3 4 5 6 7 Value := TSomeValue.Create(); try // Execute actions with Value finally Value.Free(); end;