← Back to fpsonar
Thirty rules about if, case, loops and jumps. This chapter contains both
housekeeping ("this is clearer written the other way") and genuine bug detectors
("this branch can never run"). The severity tells you which is which: major rules
here usually point at a real mistake.
Branches that cannot be right
editIdenticalBranches
editmajor · off by default
If the then and else bodies are the same code, the condition does not matter.
Either the condition is pointless or one branch was meant to differ and the edit was
never made — usually the second.
fpsonar complains about this
if IsAdmin then
Grant(AUser, 'read')
else
Grant(AUser, 'read');
fpsonar accepts this
if IsAdmin then
Grant(AUser, 'write')
else
Grant(AUser, 'read');
DuplicateConditionInChain
editmajor · off by default
In an if/else if chain the first matching branch wins, so a condition repeated
later can never be reached. Almost always a copy-paste where one comparison was not
updated.
fpsonar complains about this
if Code = 1 then Handle1
else if Code = 2 then Handle2
else if Code = 1 then Handle3; // unreachable
fpsonar accepts this
if Code = 1 then Handle1
else if Code = 2 then Handle2
else if Code = 3 then Handle3;
DuplicateCaseLabel
editmajor · off by default
The same label twice in one case. The compiler may reject it, but ranges make it
easy to overlap without noticing — 1..5 and 3 are a duplicate.
fpsonar complains about this
case Level of
1..5: Handle('low');
3: Handle('mid'); // already covered by 1..5
end;
fpsonar accepts this
case Level of
1..2: Handle('low');
3: Handle('mid');
4..5: Handle('high');
end;
SelfComparison
editmajor · off by default
Comparing something to itself is always True (or always False for <>). The
usual cause is a typo in one of two similar names.
fpsonar complains about this
if Row.Left = Row.Left then // meant Row.Right
Align;
fpsonar accepts this
if Row.Left = Row.Right then
Align;
EmptyThenWithFollowingStatement
editmajor · off by default
The classic stray semicolon. if C then ; is a complete if with an empty body, so
the statement that follows runs unconditionally — which is the opposite of what was
written.
fpsonar complains about this
if not FileExists(AName) then ;
CreateFile(AName); // runs always
fpsonar accepts this
if not FileExists(AName) then
CreateFile(AName);
MixedBooleanAndRelational
editminor · off by default
A Pascal trap with no equivalent in C: and binds tighter than =. So
A and B = C parses as A and (B = C), not (A and B) = C. If you meant the
latter, the code compiles and does something else.
fpsonar complains about this
if Flags and MaskRead = MaskRead then // parses as Flags and (MaskRead = MaskRead)
Allow;
fpsonar accepts this
if (Flags and MaskRead) = MaskRead then
Allow;
BitwiseOnBooleanOperands
editmajor · off by default
and, or and xor serve double duty: boolean logic and bit manipulation. Mixing
a boolean with an integer operand means one of them is being reinterpreted, and the
result is rarely what was intended.
fpsonar complains about this
if IsOpen and Flags then // Boolean mixed with an integer
Read;
fpsonar accepts this
if IsOpen and ((Flags and MaskRead) <> 0) then
Read;
ConditionWithSideEffect
editmajor · off by default
Pascal short-circuits and and or, so the right-hand operand may not be evaluated
at all. If it is a call with a var or out argument, whether that variable gets
written depends on the left operand — a difference that is invisible at the call
site.
fpsonar complains about this
if IsOpen and TryRead(Buffer) then // TryRead may never run
Use(Buffer);
fpsonar accepts this
if IsOpen then
if TryRead(Buffer) then
Use(Buffer);
AssignmentInsteadOfComparison
editmajor · off by default
A := where the surrounding grammar implies =. The rule limits itself to
high-confidence shapes — an assignment inside a call's argument list — so it does not
guess.
fpsonar complains about this
Log(Status := 0);
fpsonar accepts this
Log(Status = 0);
LoopBeyondCollectionEnd
editmajor · on by default
Indexing one past the last element. In Pascal a dynamic array or list runs 0 to
Count - 1, and for I := 0 to Count do is off by one.
fpsonar complains about this
for I := 0 to List.Count do
Process(List[I]);
fpsonar accepts this
for I := 0 to List.Count - 1 do
Process(List[I]);
LoopConditionNeverChanges
editmajor · off by default
If the body writes no variable the condition tests, the loop either never runs or
never stops. A while True with an exit inside is not caught, because that is a
deliberate idiom.
fpsonar complains about this
while not Done do
Process(Next); // nothing ever sets Done
fpsonar accepts this
while not Done do
begin
Process(Next);
Done := AtEnd;
end;
SingleIterationLoop
editminor · on by default
A loop whose body always leaves on the first pass is an if wearing a loop's
clothes. Say what you mean.
fpsonar complains about this
for I := 0 to List.Count - 1 do
begin
Result := List[I];
Break;
end;
fpsonar accepts this
if List.Count > 0 then
Result := List[0];
Shapes that are clearer written differently
editCollapsibleNestedIf
editminor · off by default
An if that is the entire body of another if, with no else on either, is one
condition joined by and.
fpsonar complains about this
if AName <> '' then
if FileExists(AName) then
Load(AName);
fpsonar accepts this
if (AName <> '') and FileExists(AName) then
Load(AName);
RedundantElseAfterExit
editminor · off by default
If the then branch ends in exit, break, continue, halt or raise, control
never reaches the else, so the else and its indentation are noise.
fpsonar complains about this
if AName = '' then
exit
else
Load(AName);
fpsonar accepts this
if AName = '' then
exit;
Load(AName);
NegatedConditionWithElse
editminor · off by default
if not C then X else Y makes a reader negate mentally to follow the second branch.
Invert the condition and swap.
fpsonar complains about this
if not IsValid then
Reject
else
Accept;
fpsonar accepts this
if IsValid then
Accept
else
Reject;
SwitchOnBooleanExpression
editminor · off by default
A case over a Boolean has exactly two outcomes, which is what if/else is for.
fpsonar complains about this
case IsValid of
True: Accept;
False: Reject;
end;
fpsonar accepts this
if IsValid then
Accept
else
Reject;
CaseAtLeastTwoItems
editminor · on by default
A case with a single branch is an if with more ceremony.
fpsonar complains about this
case Level of
1: Handle('low');
end;
fpsonar accepts this
if Level = 1 then
Handle('low');
ExhaustiveCaseStatement
editminor · on by default
A case over an enumeration that does not handle every value. Adding a value to the
enumeration later will silently fall through here. Either handle every value or add
an else, so the omission is a decision rather than an oversight.
fpsonar complains about this
type
TLevel = (lvLow, lvMid, lvHigh);
case Level of
lvLow: Handle('low');
lvMid: Handle('mid');
end; // lvHigh silently ignored
fpsonar accepts this
case Level of
lvLow: Handle('low');
lvMid: Handle('mid');
lvHigh: Handle('high');
end;
RedundantJump
editminor · on by default
A jump that goes where control was already going — a Continue as the last
statement of a loop body, an exit as the last statement of a routine.
fpsonar complains about this
procedure Run;
begin
Process;
exit;
end;
fpsonar accepts this
procedure Run;
begin
Process;
end;
RedundantAssignedCheckBeforeFree
editminor · on by default
Free is already safe on nil, so guarding it adds a line that cannot change the
outcome.
fpsonar complains about this
if Assigned(L) then
L.Free;
fpsonar accepts this
L.Free;
NoSelfAssignment
editminor · on by default
X := X does nothing. Usually a typo where one side should name something else.
fpsonar complains about this
FName := FName;
fpsonar accepts this
FName := AName;
RedundantBooleanLiteral
editminor · on by default
Comparing a Boolean to True or False adds a step. The expression is already the
value you want.
fpsonar complains about this
if IsValid = True then
Accept;
fpsonar accepts this
if IsValid then
Accept;
NilCheckViaAssigned
editminor · on by default
Assigned(X) and X <> nil mean the same for a pointer or object; Assigned reads
better and works for procedural values too.
fpsonar complains about this
if Reader <> nil then
Reader.Read;
fpsonar accepts this
if Assigned(Reader) then
Reader.Read;
NoPascalStyleResultAssignment
editminor · on by default
Assigning to the function's own name works, but Result is clearer and, unlike the
function name, can be read back before returning.
fpsonar complains about this
function Total: Integer;
begin
Total := 0;
end;
fpsonar accepts this
function Total: Integer;
begin
Result := 0;
end;
RoutineResultAssigned
editmajor · on by default
A function that can return without assigning Result. The caller then gets whatever
happened to be in memory. This is a real bug and the compiler's own warning misses
many cases.
fpsonar complains about this
function FindName(AId: Integer): string;
begin
if AId > 0 then
Result := Lookup(AId);
end; // AId <= 0 returns garbage
fpsonar accepts this
function FindName(AId: Integer): string;
begin
Result := '';
if AId > 0 then
Result := Lookup(AId);
end;
Statements to avoid
editNoGoto
editmajor · on by default
goto makes control flow unreadable and defeats most reasoning about a routine.
Structured statements cover essentially every real need.
fpsonar complains about this
label Done;
begin
if Bad then goto Done;
Process;
Done:
end;
fpsonar accepts this
begin
if Bad then exit;
Process;
end;
NoWith
editmajor · on by default
with hides which object a name belongs to, and when two with scopes both provide
a name the winner is decided by rules few people remember. Worse, adding a member to
a class can silently change what an existing with body refers to.
fpsonar complains about this
with Customer do
begin
Name := 'x'; // Customer.Name? or a local Name?
Save;
end;
fpsonar accepts this
Customer.Name := 'x';
Customer.Save;
NoEmptyBlock
editmajor · on by default
A begin..end with nothing in it. Either code is missing or the block is left over.
fpsonar complains about this
if IsValid then
begin
end;
fpsonar accepts this
if IsValid then
Accept;
RoutineNotEmpty
editminor · on by default
A routine with an empty body. Legitimate for an abstract stub or an interface
placeholder, but often an unfinished implementation. Mark it abstract if that is
what you mean.
fpsonar complains about this
procedure TReport.Build;
begin
end;
fpsonar accepts this
procedure TReport.Build; virtual; abstract;
NoInlineAssembly
editmajor · on by default
An asm block ties the unit to one CPU and is invisible to every analysis tool,
including this one. Sometimes necessary; always worth isolating in a small unit with
a portable fallback.
fpsonar complains about this
function Swap(A: LongWord): LongWord;
begin
asm
mov eax, A
bswap eax
END;
end;
fpsonar accepts this
function Swap(A: LongWord): LongWord;
begin
Result := ((A and $FF) shl 24) or ((A and $FF00) shl 8)
or ((A shr 8) and $FF00) or ((A shr 24) and $FF);
end;
ExceptionRaised
editmajor · on by default
An exception object created but never raised. The construction succeeds, the object leaks, and the error you meant to report never happens.
fpsonar complains about this
if Bad then
EConfigMissing.Create('missing'); // constructed, not raised
fpsonar accepts this
if Bad then
raise EConfigMissing.Create('missing');
UnreachableCode
editmajor · off by default
A statement no control path through its routine reaches. Everything after an unconditional
Exit, Break, Continue, Halt or raise, until control can arrive again.
Unlike most style findings this one usually means something: the code was meant to run, and
an Exit was added above it — or moved — without anyone noticing what was stranded below.
This rule is built on the same control-flow graph as the rules in
values through a routine, so it follows the real paths rather than pattern-matching the
statement after a return.
fpsonar complains about this
function Load(const aName: string): Boolean;
begin
Result := Parse(aName);
Exit;
LogResult(Result); // nothing reaches this
end;
fpsonar accepts this
function Load(const aName: string): Boolean;
begin
Result := Parse(aName);
LogResult(Result);
end;
Related chapters
editComparisons that are fixed by a type's range, and arithmetic that cannot work, are in expressions. Exception handling itself is in exceptions. Rules that follow values along these same paths — read before written, written and never read — are in values through a routine.
See also
edit- fpsonar — what fpSonar is, and how to run it
← Back to fpsonar