2

I got this warning on Sonar as a violation. I want proper solution to remove this warning from sonar.

My code is like this:

void method(){
try {
  int x;
  x=5;
 }
 catch{
    //handling code
 }
}

I got warning for this code like:

'5' is a magic number.

So, I want proper solution to remove such warning.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Oomph Fortuity
  • 5,710
  • 10
  • 44
  • 89

3 Answers3

6

Magic number is the direct usage of the number in the code(i.e., hard-coded number in the code in your case using 5 directly)

to get rid of the warning try this:

 int x;
 static final int SOME_NUMBER=5;
 x=SOME_NUMBER;
PermGenError
  • 45,977
  • 8
  • 87
  • 106
6

Sonar is asking you to document why you use that particular number by giving it a name. You can do so by declaring a constant (with an expressive name):

static final int NUMBER_OF_RETRIES = 5;

and then use that constant instead of the "magic" number, thereby expressing the intent of that assignment more clearly:

x = NUMBER_OF_RETRIES;

This also has the advantage that if NUMBER_OF_RETRIES needs to be changed, you can do so in one place, rather than whereever that "magic" number is used.

meriton
  • 68,356
  • 14
  • 108
  • 175
3

Well, I'm aware that this question has already been answered satisfactorily, but I'd like to add here the own Sonar explanation, since it's quite well elaborated:

A magic number is a number that comes out of nowhere, and is directly used in a statement. Magic numbers are often used, for instance to limit the number of iterations of a loops, to test the value of a property, etc.

Using magic numbers may seem obvious and straightforward when you're writing a piece of code, but they are much less obvious and straightforward at debugging time.

That is why magic numbers must be demystified by first being assigned to clearly named variables before being used.

-1, 0 and 1 are not considered magic numbers.

Noncompliant Code Example

public static void doSomething() {
  for(int i = 0; i < 4; i++){                 // Noncompliant, 4 is a magic number
      ...
  }
}

Compliant Solution

public static final int NUMBER_OF_CYCLES = 4;
public static void doSomething() {
  for(int i = 0; i < NUMBER_OF_CYCLES ; i++){
    ...
  }
}

Exceptions

This rule ignores hashCode methods.

Thales Valias
  • 563
  • 5
  • 11