← Back to fpsonar
Twenty-six rules. Roughly half are about inheritance going quietly wrong — a method that looks like an override but is not, a constructor that never chains — and half are about how a class presents itself.
Two facts most of these rules depend on:
- A method is only polymorphic if it is
virtual(oroverride). Declaring a
method with the same name as an ancestor's does not override it; it hides it, and
calls through a base reference still reach the ancestor.
- Class references are pointers.
A = Bon two class variables compares
addresses, not contents.
Inheritance that does not do what it looks like
editMethodHidesVirtualWithoutOverride
editmajor · off by default
A method with the same signature as an overridable ancestor method, declared without
override. It compiles, and it silently hides rather than overrides — so a call
through a base-class reference runs the ancestor's version. This is one of the most
effective silent bugs in Object Pascal.
If hiding is what you want, say so with reintroduce.
fpsonar complains about this
type
TBase = class
procedure Save; virtual;
end;
TDerived = class(TBase)
procedure Save; // hides, does not override
end;
fpsonar accepts this
type
TDerived = class(TBase)
procedure Save; override;
end;
OverrideChangesDefaultParameterValue
editmajor · off by default
Default parameter values are resolved at the call site, from the static type — not from the object's actual class. So an override that declares a different default is wrong at every polymorphic call, and correct only when called through its own type. Nothing warns you.
fpsonar complains about this
type
TBase = class
procedure Save(ABackup: Boolean = True); virtual;
end;
TDerived = class(TBase)
procedure Save(ABackup: Boolean = False); override; // different default
end;
fpsonar accepts this
type
TDerived = class(TBase)
procedure Save(ABackup: Boolean = True); override;
end;
ConstructorInherited
editmajor · on by default
A constructor that never calls inherited. The ancestor's initialisation does not
run, so its fields hold whatever was in memory.
fpsonar complains about this
constructor TReport.Create;
begin
FLines := TStringList.Create;
end;
fpsonar accepts this
constructor TReport.Create;
begin
inherited Create;
FLines := TStringList.Create;
end;
DestructorInherited
editmajor · on by default
The same on the way out: without inherited Destroy the ancestor's cleanup never
runs, and whatever it owned leaks.
fpsonar complains about this
destructor TReport.Destroy;
begin
FLines.Free;
end;
fpsonar accepts this
destructor TReport.Destroy;
begin
FLines.Free;
inherited Destroy;
end;
InheritedCreateNotFirstStatement
editmajor · off by default
inherited Create should come first. Anything before it touches fields the ancestor
has not initialised yet — and if the ancestor's constructor raises, you have already
allocated things nobody will free.
fpsonar complains about this
constructor TReport.Create;
begin
FLines := TStringList.Create; // before the ancestor is ready
inherited Create;
end;
fpsonar accepts this
constructor TReport.Create;
begin
inherited Create;
FLines := TStringList.Create;
end;
InheritedDestroyNotLastStatement
editmajor · off by default
The mirror image: inherited Destroy goes last. After it runs, the ancestor's part
of the object is gone, so anything following touches destroyed state.
fpsonar complains about this
destructor TReport.Destroy;
begin
inherited Destroy;
FLines.Free; // the object is already partly gone
end;
fpsonar accepts this
destructor TReport.Destroy;
begin
FLines.Free;
inherited Destroy;
end;
ConstructorNotVirtualInPolymorphicHierarchy
editmajor · off by default
If a class has virtual methods and descendants redeclare its constructor, the
constructor should be virtual too — otherwise creating an instance through a class
reference (TBaseClass) runs the base constructor rather than the descendant's.
fpsonar complains about this
type
TBase = class
constructor Create; // not virtual
procedure Run; virtual;
end;
TDerived = class(TBase)
constructor Create;
end;
fpsonar accepts this
type
TBase = class
constructor Create; virtual;
procedure Run; virtual;
end;
TDerived = class(TBase)
constructor Create; override;
end;
AbstractMethodCalledDirectly
editmajor · off by default
An inherited call to a method the ancestor declares abstract. There is no
implementation to reach, so this raises at run time.
fpsonar complains about this
procedure TDerived.Run;
begin
inherited Run; // TBase.Run is abstract
end;
fpsonar accepts this
procedure TDerived.Run;
begin
DoRun;
end;
InstantiatesClassWithAbstractMethods
editmajor · off by default
Constructing a class that still has an unimplemented abstract method. The construction succeeds; the failure comes later, when something calls the missing method.
fpsonar complains about this
type
TBase = class
procedure Run; virtual; abstract;
end;
begin
Obj := TBase.Create; // Run has no implementation
end;
fpsonar accepts this
begin
Obj := TConcreteRunner.Create;
end;
OverrideOnlyCallsInherited
editminor · on by default
An override whose whole body is inherited. It changes nothing and can be deleted —
the ancestor's method is already what runs.
fpsonar complains about this
procedure TDerived.Save;
begin
inherited Save;
end;
fpsonar accepts this
// remove the override entirely
RedundantInherited
editminor · on by default
An inherited statement that binds to nothing — no overridable ancestor method of
that name exists. Harmless, but it suggests the author believed something was being
extended.
fpsonar complains about this
procedure TReport.Build;
begin
inherited; // no ancestor Build
DoBuild;
end;
fpsonar accepts this
procedure TReport.Build;
begin
DoBuild;
end;
Interfaces
editInterfaceUniqueGuid
editmajor · on by default
An interface without a GUID cannot be used with as, Supports or
QueryInterface — those all look the interface up by its identifier. Add one with
Ctrl+Shift+G in an IDE, or by hand.
fpsonar complains about this
type
IReader = interface
function Read: string;
end;
fpsonar accepts this
type
IReader = interface
['{2A1B4C6D-8E9F-4A0B-9C1D-2E3F4A5B6C7D}']
function Read: string;
end;
InterfaceWithoutGuidUsedDynamically
editmajor · off by default
The consequence of the above, caught at the use site: an as, Supports or
QueryInterface naming an interface that has no GUID. This fails at run time rather
than compile time.
fpsonar complains about this
if Supports(Obj, IReader, R) then // IReader declares no GUID
R.Read;
fpsonar accepts this
// give IReader a GUID, then:
if Supports(Obj, IReader, R) then
R.Read;
SupportsResultIgnored
editmajor · off by default
Supports returns whether the query succeeded. Calling it as a statement discards
that, so the code proceeds as though it worked.
fpsonar complains about this
Supports(Obj, IReader, R);
R.Read; // R may be nil
fpsonar accepts this
if Supports(Obj, IReader, R) then
R.Read;
InterfaceNotEmpty
editminor · on by default
An interface declaring no methods or properties. Sometimes deliberate — a marker interface — but usually unfinished.
fpsonar complains about this
type
IReader = interface
end;
fpsonar accepts this
type
IReader = interface
function Read: string;
end;
NoObjectAsInterface
editmajor · on by default
Assigning an object to a COM interface variable brings it under reference counting,
while your code still manages it manually. Whichever side frees first, the other is
wrong. Use {$INTERFACES CORBA} for interfaces on manually-managed objects — CORBA
interfaces are not reference-counted.
fpsonar complains about this
var
R: IReader; // COM interface: reference-counted
begin
R := FReader; // FReader is owned by this class
end;
fpsonar accepts this
{$INTERFACES CORBA}
type
IReader = interface
function Read: string;
end;
AssignedOnNonReference
editmajor · off by default
Assigned tests whether a reference is nil. Applied to a record, a static array
or an ordinal there is no reference to test, so the answer is meaningless.
fpsonar complains about this
var
R: TMyRecord;
begin
if Assigned(R) then
Use(R);
end;
fpsonar accepts this
var
P: PMyRecord;
begin
if Assigned(P) then
Use(P^);
end;
ComparingClassReferencesWithEquals
editminor · off by default
= on two class variables compares addresses: true only if both name the same
object. If you meant "equal contents", write a comparison method. Off by default and
cfLow confidence, because identity comparison is often exactly what was wanted.
fpsonar complains about this
if CustomerA = CustomerB then // same object, or equal customers?
Merge;
fpsonar accepts this
if CustomerA.SameAs(CustomerB) then
Merge;
How a class presents itself
editFieldsNotPublic
editmajor · on by default
A public field lets any caller change state without the class knowing. A property over a private field costs nothing and leaves you able to add validation later without changing every call site.
fpsonar complains about this
type
TCustomer = class
public
Name: string;
end;
fpsonar accepts this
type
TCustomer = class
private
FName: string;
public
property Name: string read FName write FName;
end;
PublicFieldAndPropertyForSameStorage
editmajor · off by default
Storage exposed twice — once directly as a public field, once through a property. Callers can bypass the property, so any validation it performs is optional.
fpsonar complains about this
type
TCustomer = class
public
Name: string;
property CustomerName: string read Name write Name;
end;
fpsonar accepts this
type
TCustomer = class
private
FName: string;
public
property Name: string read FName write FName;
end;
PropertyAccessorVisibilityWiderThanProperty
editmajor · off by default
A private property whose getter or setter is public. The property's visibility then means nothing — callers use the accessor directly.
fpsonar complains about this
type
TReport = class
public
function GetCount: Integer;
private
property Count: Integer read GetCount; // GetCount is reachable anyway
end;
fpsonar accepts this
type
TReport = class
private
function GetCount: Integer;
property Count: Integer read GetCount;
end;
PropertyGetterWithSideEffect
editmajor · off by default
A getter that writes a field of its own class. Reading a property should not change the object: it makes debugging strange, and reading twice can give different answers. A cache field is the legitimate exception.
fpsonar complains about this
function TReport.GetCount: Integer;
begin
Inc(FReadCount); // reading changes the object
Result := FLines.Count;
end;
fpsonar accepts this
function TReport.GetCount: Integer;
begin
Result := FLines.Count;
end;
ClassHelperHidesAncestorMethod
editmajor · off by default
A helper method whose name the extended type already declares. The real method wins, so the helper method is never called — silently.
fpsonar complains about this
type
TListHelper = class helper for TStringList
procedure Clear; // TStringList.Clear already exists
end;
fpsonar accepts this
type
TListHelper = class helper for TStringList
procedure ClearAndTrim;
end;
TopLevelClassInheritsTObject
editminor · on by default
type TFoo = class without an ancestor descends from TObject implicitly. Saying
so makes the hierarchy explicit for a reader.
fpsonar complains about this
type
TReport = class
end;
fpsonar accepts this
type
TReport = class(TObject)
end;
VisibilityAscendingOrder
editminor · on by default
Visibility sections should run from most restricted to least — private,
protected, public, published. A reader scanning for the public surface then
finds it in one place.
fpsonar complains about this
type
TReport = class
public
procedure Build;
private
FLines: TStringList;
end;
fpsonar accepts this
type
TReport = class
private
FLines: TStringList;
public
procedure Build;
end;
DeclarationsFollowVisibilityOrder
editminor · on by default
Within a section: fields, then methods, then properties. Consistency makes a class skimmable.
fpsonar complains about this
type
TReport = class
private
procedure Build;
FLines: TStringList;
end;
fpsonar accepts this
type
TReport = class
private
FLines: TStringList;
procedure Build;
end;
Closures and nested routines
editNoInlineVarCapturedByAnonMethod
editmajor · on by default
An anonymous method that captures a variable whose lifetime is shorter than the closure's. When the closure runs later, the variable is gone and the closure reads whatever is now on the stack.
fpsonar complains about this
procedure Register;
var
I: Integer;
begin
for I := 0 to 9 do
Callbacks.Add(procedure begin Log(I); end); // I is gone by then
end;
fpsonar accepts this
procedure AddCallback(AValue: Integer);
begin
Callbacks.Add(procedure begin Log(AValue); end);
end;
NoNestedRoutineAsProcValue
editmajor · on by default
Taking the address of a nested routine and storing it somewhere. The nested routine depends on its enclosing stack frame, which is gone once the outer routine returns.
fpsonar complains about this
procedure Setup;
procedure Handler;
begin
end;
begin
OnEvent := @Handler; // outlives Setup's frame
end;
fpsonar accepts this
procedure TOwner.Handler;
begin
end;
procedure TOwner.Setup;
begin
OnEvent := @Handler; // a method: no stack dependency
end;
Related chapters
editNaming conventions for classes and interfaces are in naming.
Constructor and destructor memory concerns — fields not freed, freeing Self — are
in memory and lifetime.
See also
edit- fpsonar — what fpSonar is, and how to run it
← Back to fpsonar