Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic number sonar violation on JPA annotations

We are using sonar for managing our code quality. I have a problem with "Magic Number" violation for JPA annotation like that:

@NotNull
@Size(min = 1, max = 300)
@Column(name = "NAME")

Is this a true violation for annotation?

If not, how can we deal this kind of Sonar violation?

like image 837
Saeed Zarinfam Avatar asked Sep 04 '12 06:09

Saeed Zarinfam


3 Answers

The Magic Number violation doesn't understand if this number appears in an annotation or not. IMHO this is a false-positive and you can deal with it in two ways. Either disable this rule in your quality profile or create a MAGICNUMBER class and list all the numbers you're using as static properties. For example look the following class

public final class MAGICNUMBER {
public static final int L8000 = 8000;
public static final int L300 = 300;

}

Then you can use it in your class like this

@NotNull
@Size(min = 1, max = MAGICNUMBER.L300)
@Column(name = "NAME")
like image 88
ppapapetrou Avatar answered Sep 21 '22 23:09

ppapapetrou


I'm not sure how it was in 2012, but finding this now, there appears to be a way to disable it just for annotations in v 3.3.2, and surely above that

Disable magic number in annotation. Shown is Sonar 3.3.2

like image 23
Matt Broekhuis Avatar answered Sep 19 '22 23:09

Matt Broekhuis


You can edit the rule in your checkstyle file so it doesn't take into account annotation, hashcode methods or specific numbers.

<module name="MagicNumber">
    <property name="ignoreNumbers" value="-1, 0, 1, 2, 3"/>
    <property name="ignoreHashCodeMethod" value="true" />
    <property name="ignoreAnnotation" value="true" />
</module>
like image 32
TheBakker Avatar answered Sep 17 '22 23:09

TheBakker