integrated-application-development / integrated-application-development/sonar-delphi

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

Open
#423 1 comment 0 reactions 0 assignees View on GitHub
feature rule
Dominant language
Java
Stars
159
Forks
31
Avg merge
5d 4h
Merged PRs (30d)
4

Description

### Prerequisites

- [x] This rule has not already been suggested.
- [x] This should be a new rule, not an improvement to an existing rule.
- [x] 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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.