Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's checkstyle, MagicNumberCheck

I am using checkstyle to get reportings about my source-code. This question is about the MagicNumberCheck.

I am using Date/(org.joda.)DateTime in my source code like this:

DateTime dateTime = new DateTime(2013, 2, 27, 23, 0):
dateTime.plusHours(57);

Is there a way to suppress the MagicNumberCheck notifications if the magic number is within a Date or DateTime?

like image 596
Markus Schulte Avatar asked Mar 04 '13 12:03

Markus Schulte


People also ask

Is a magic number Magicnumber checkstyle?

Class MagicNumberCheck. Checks that there are no "magic numbers" where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers. Constant definition is any variable/field that has 'final' modifier.

Is 100 a magic number?

Practical Magic Number rule: A literal is a not a magic number if the most meaningful variable name for it is the same as the spoken name of the literal. So by this logic, 100 is NOT a magic number.

How do I get rid of magic numbers in Java?

The direct answer is that named constants is the only way to avoid having magic numbers in your code.


1 Answers

You can use SuppressionCommentFilter check to do this.

Configure the properties values like (in your checkstyle configuration file)

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="Check\:OFF\: ([\w\|]+)"/>
  <property name="onCommentFormat" value="Check\:ON\: ([\w\|]+)"/>
  <property name="checkFormat" value="$1"/>
</module>

Now for the required lines, you can do like

//Check:OFF: MagicNumber
DateTime dateTime = new DateTime(2013, 2, 27, 23, 0):
dateTime.plusHours(57);
//Check:ON: MagicNumber

This will only suppress MagicNumber checks, the rest checks will work here.

You can suppress Multiple checcks too, like

//Check:OFF: MagicNumber|Indentation
Code Here
//Check:ON: MagicNumber|Indentation

this will suppress only MagicNumber and Indentation Checks. Other checks will work fine.

like image 117
Denim Datta Avatar answered Sep 24 '22 17:09

Denim Datta