Skip to content

New rule: Records should be fully initialized in constructors #131

Open
@Chadehoc

Description

@Chadehoc

Prerequisites

  • This rule has not already been suggested.
  • This should be a new rule, not an improvement to an existing rule.
  • This rule would be generally useful, not specific to my code or setup.

Suggested rule title

RecordsShouldBeFullyInitialized

Rule description

There was discussion in #127 about initializing records through a constructor: should constructors be trusted to properly initialize their results? It was suggested that it should be a separate rule.

This rule would check that even within a constructor, a proper initialization is done by:

  • Assigning the result (to Default(T), or a constant, or another initialized variable...)
  • Calling another constructor

Calling Initialize isn't enough, because it will only properly initialize managed fields (unless the rule can test that every field in a record is either managed, or a sub-record having recursively the same property).

Rationale

Suppose a record has only two fields, X and Y. The following constructor could be thought harmless:

constructor TMyRecord.Create(AValX: Integer);
begin
  Self.X := AValX;
  Self.Y := 0;
end;

But if you add another field Z later, there is the risk of the constructor adaptation being forgotten.

The following is guaranteed to evolve better:

constructor TMyRecord.Create(AValX: Integer);
begin
  Self := Default(TMyRecord); // or calling another constructor
  Self.X := AValX;
end;

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or requestruleImprovements or additions to rules

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions