Fpsonar generics and closures

← Back to fpsonar

Six rules about the newer parts of the language: generic templates and their constraints, anonymous methods and what they capture, and attributes that no RTTI can reach.

All are off by default.

Generics

edit

GenericConstraintUnused

edit

minor · off by default

A template parameter declares a type constraint that none of the generic's routines rely on. The constraint narrows what callers may specialize with, and buys nothing in return.

Either the constraint is left over from an earlier design, or a routine was meant to use it and does not — both are worth a look.

fpsonar complains about this

type
  generic TBox<T: TObject> = class      // constrained to classes...
    FItem: T;
    procedure Store(aItem: T);
  end;

procedure TBox.Store(aItem: T);
begin
  FItem := aItem;                       // ...but only ever assigned
end;

fpsonar accepts this

type
  generic TBox<T> = class
    FItem: T;
    procedure Store(aItem: T);
  end;

Keeping the constraint and using it is equally fine — FItem.Free in a destructor makes T: TObject load-bearing.

SpecializationOfUnconstrainedGeneric

edit

info · off by default

A specialization of a generic that declares template parameters and constrains none of them. Nothing is wrong with the code; the report is a prompt to consider whether the template should say more about what it accepts.

Being info, this is the quietest rule in the chapter. On a codebase using generics as plain containers it will fire a great deal, and that is not a defect.

fpsonar complains about this

type
  generic TList<T> = class ... end;

  TIntList = specialize TList<Integer>;

fpsonar accepts this

type
  generic TList<T: TObject> = class ... end;

  TThingList = specialize TList<TThing>;

NestedGenericSpecializationDepth

edit

minor · off by default · parameter: maxDepth, default 3

A specialization nesting more levels of specialization than the configured maximum. Deeply nested types are legal and compile, but they are hard to read at the declaration and worse in an error message, where the compiler prints the whole expansion.

{
  "rules": {
    "NestedGenericSpecializationDepth": {
      "enabled": true,
      "params": { "maxDepth": 2 }
    }
  }
}

fpsonar complains about this

type
  TDeep = specialize TMap<string,
            specialize TList<
              specialize TPair<Integer,
                specialize TBox<TThing>>>>;      // four levels

fpsonar accepts this

type
  TThingBox  = specialize TBox<TThing>;
  TThingPair = specialize TPair<Integer, TThingBox>;
  TDeep      = specialize TMap<string, specialize TList<TThingPair>>;

Anonymous methods

edit

AnonymousMethodCapturesLoopVariable

edit

major · off by default

An anonymous method that captures the control variable of an enclosing for loop declared outside the loop. Pascal has one variable for the whole loop, not one per iteration, so every closure the loop creates sees the same variable — and by the time any of them runs, it holds whatever the loop left behind.

This is the rule in this chapter most likely to be pointing at a real bug. The symptom is several closures that all behave as though they were created on the last iteration.

fpsonar complains about this

var
  i: Integer;
  lActions: array of TProc;
begin
  SetLength(lActions, 3);
  for i := 0 to 2 do
    lActions[i] := procedure begin WriteLn(i); end;   // all three print the same value

fpsonar accepts this

function MakeAction(aValue: Integer): TProc;
begin
  Result := procedure begin WriteLn(aValue); end;     // aValue is per-call
end;

...
  for i := 0 to 2 do
    lActions[i] := MakeAction(i);

The fix is to give each closure its own variable. A function parameter is the simplest way; Pascal has no per-iteration binding to rely on.

AnonymousMethodCapturesSelf

edit

info · off by default

An anonymous method whose body reaches the enclosing instance — through Self, or through a field, method or property named without a qualifier. The closure then keeps working only for as long as that instance lives.

Nothing is wrong when the closure runs and finishes before the object is freed. It matters when the closure outlives its creator: stored in a list, handed to a timer, queued for another thread. Being info, the rule tells you the capture happened and leaves the judgement to you.

fpsonar complains about this

procedure TReport.Schedule;
begin
  FQueue.Add(procedure
    begin
      Render;                 // a method of Self — the closure captures Self
    end);
end;

fpsonar accepts this

procedure TReport.Schedule;
var
  lText: string;
begin
  lText := FTitle;            // copy what the closure needs
  FQueue.Add(procedure
    begin
      WriteLn(lText);
    end);
end;

Attributes

edit

AttributeOnNonRttiMember

edit

minor · off by default

An attribute written on a field, method or property that sits outside a published section. Attributes are read back at run time through RTTI, and RTTI does not reach members that are not published — so the annotation compiles, and then nothing can ever find it.

Typically found where a serializer or ORM is driven by attributes and one field silently fails to take part.

Members declared before any visibility keyword are never judged: what that implicit first section means depends on {$M} state the rule does not track.

fpsonar complains about this

type
  TReport = class
  private
    [JsonName('id')]
    FId: Integer;             // private — no RTTI reaches the attribute
  end;

fpsonar accepts this

type
  TReport = class
  private
    FId: Integer;
  published
    [JsonName('id')]
    property Id: Integer read FId write FId;
  end;
edit

Rules about classes, visibility and properties generally are in classes and interfaces. Anonymous methods that are never called, like any unused declaration, are covered in unused code.

See also

edit
  • fpsonar — what fpSonar is, and how to run it

← Back to fpsonar