Search code examples
javainitializationfieldbigdecimalcheckstyle

How to avoid magic number warning when initialize static field (for example BigDecimal)?


I have static field

private static final BigDecimal MAX_AMOUNT = BigDecimal.valueOf(299_999L);

And I get warning from CheckStyle that 299_999L is magic number. How can I avoid this - 299_999 is just long transform into specified BigDecimal.

I did not find in CheckStyle documentation any suitable solution.

EDIT: It comes out when I type for example:

private static final BigDecimal MAX_AMOUNT = BigDecimal.valueOf(299_999L).setScale(4, BigDecimal.ROUND_HALF-EVEN)

Solution

  • After your clarifying comment, I can say that the reason for the warning is in the way the MagicNumber check works. If the potential magic number is in a field definition, and that field is final, then it is not flagged as long as all parent tokens in the AST up to the node representing the field definition are in a certain list.

    This is quite confusing, and I think that to a normal user, it seems arbitrary. But static code analysis is often about heuristics.

    The good thing is you can influence this behavior. Configure the check like this:

    <module name="MagicNumber">
        <property name="constantWaiverParentToken"
            value="TYPECAST, METHOD_CALL, EXPR, ARRAY_INIT, UNARY_MINUS, UNARY_PLUS, ELIST, STAR, ASSIGN, PLUS, MINUS, DIV, LITERAL_NEW, DOT"/>
    </module>
    

    The value of constantWaiverParentToken is the default plus DOT added to the end. This allows for more complex expressions. You need at least Checkstyle 6.11 for this to work.