3

By definition,

"Magic number" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.

This is a perfect example of a magic number

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

and should be changed to something meaningful like

    for(int i = 0; i < NUMBER_OF_CYCLES ; i++){
        ...

But Sonar throws errors for indexNumbers too. For instance, I have a DAO class where insert statement has almost 50+ columns and sonar throws error for

ps.setString(1 ,...)

I am sure this is more readable than

ps.setString(INDEX_ONE ,...)

Is there anything wrong in my understanding? or Is it a bug in Sonar?

Vamsidhar
  • 822
  • 11
  • 24

1 Answers1

2

Technically and factually, it's not a bug: the rule finds that the code uses arbitrary numbers.

However, I find reasonable to think that this very particular use case, with fixed indices for column numbers, should be considered a false positive. And indeed, I see no point in trying to "fix" the code. So my suggestion is to either mark these individual issues as False positive or Won't fix in SonarQube, or to exclude this rule from analyzing your DAO classes.

Mithfindel
  • 4,553
  • 1
  • 23
  • 32