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 theelse
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
andpublished
- 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:
- Fields
- Constructors
- Destructors
- Overridden inherited functions
- Newly introduced virtual functions
- Newly introduced non-virtual functions
- 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 frominstance
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;