Skip to content

New rule: Magic numbers (or literals) should be replaced with symbolic constants #423

@Daniel-Tr

Description

@Daniel-Tr

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

Magic numbers (or literals) should be replaced with symbolic constants

Rule description

Magic values are numbers or other literals that appear inlne in code without any obvious meaning. This rule should identify such literals and report them to be replaced with a symbolic constant. Simple examples can be seen with error codes or scientific constants:

if e.ErrorCode = 5 then WriteLn('You may not pass!');

would be better as:

if e.ErrorCode = ERROR_ACCES_DENIED then WriteLn('You may not pass!');

Note: not every number is a magic value. I would neither consider 0 nor 1 in this code a magic value:

for (var i := 0 to myList.Count - 1) do

If found a good description of such a rule here (not mine!): https://refactoring.guru/replace-magic-number-with-symbolic-constant

Rationale

Magic values (most often numbers, applies to other literals as well though) make it harder to read, understand and maintain code. By replacing them with a symbolic constant, one gains the benefits of

  • a single/reusable point of definition that can be updated when needed
  • a meaningful/symbolic name that describes and documents the contents and improves readability

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or requestruleImprovements or additions to rulestriageThis needs to be triaged by a maintainer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions