org.sonar.plugins.csharp.S109.html Maven / Gradle / Ivy
A magic number is a hard-coded numerical value that may lack context or meaning. They should not be used because they can make the code less
readable and maintainable.
Why is this an issue?
Magic numbers make the code more complex to understand as it requires the reader to have knowledge about the global context to understand the
number itself. Their usage may seem obvious when writing the code, but it may not be the case for another developer or later once the context faded
away. -1, 0, and 1 are not considered magic numbers.
Exceptions
This rule doesn’t raise an issue when the magic number is used as part of:
- the
GetHashCode
method
- a variable/field declaration
- the single argument of an attribute
- a named argument for a method or attribute
- a constructor call
- a default value for a method argument
How to fix it
Replacing them with a constant allows us to provide a meaningful name associated with the value. Instead of adding complexity to the code, it
brings clarity and helps to understand the context and the global meaning.
Code examples
Noncompliant code example
public void DoSomething()
{
for (int i = 0; i < 4; i++) // Noncompliant, 4 is a magic number
{
...
}
}
Compliant solution
private const int NUMBER_OF_CYCLES = 4;
public void DoSomething()
{
for (int i = 0; i < NUMBER_OF_CYCLES; i++) // Compliant
{
...
}
}