Java's checkstyle, MagicNumberCheck

Markus Schulte picture Markus Schulte · Mar 4, 2013 · Viewed 7.4k times · Source

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?

Answer

Denim Datta picture Denim Datta · Aug 14, 2013

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.