#294 [patch] New pattern: check for rough values of known constants like Math.PI (patch included)

3.0.0
closed-fixed
5
2014-06-19
2013-11-23
No

I wrote a small detector which detects rough values of known constants. For example, if code uses "3.1415" double constant, it will report the following:

Rough value of Math.PI found: 3.1415

Rough value of known constant found
It's recommended to use the predefined constant for code clarity and
better precision.

Bug kind and pattern: CNT - CNT_ROUGH_CONSTANT_VALUE

It looks for Math.E, Math.PI, 2*Math.PI, Math.PI/2, etc. It detects numbers which are either too close to the original constant or equal to rounded (or truncated) constant value. For example, it will detect "3.1415" and "3.1416", but not "3.1415123", because in the latter case it seems that the programmer meant something different.

I wrote the detector (findbugs/src/java/edu/umd/cs/findbugs/detect/FindRoughConstants.java), tests (findbugsTestCases/src/java/FindRoughConstantsTest.java) and added the corresponding lines to findbugs/etc/messages.xml and findbugs/etc/findbugs.xml.

Such detectors exist in some other static code analyzers like PVS-Studio for C++:
http://www.viva64.com/en/d/0241/
According to their experience, explicit usage of PI constant is quite common:
http://www.viva64.com/en/examples/v624/
Thus I believe that in Java world such cases occur as well and this detector will be useful.

Congratulations on the release of version 2.0.3!

1 Attachments

Discussion

  • Andrey Loskutov

    Andrey Loskutov - 2014-06-19
    • labels: new bug pattern --> new bug pattern, patch
    • summary: New pattern: check for rough values of known constants like Math.PI (patch included) --> [patch] New pattern: check for rough values of known constants like Math.PI (patch included)
    • assigned_to: Andrey Loskutov
     
  • Andrey Loskutov

    Andrey Loskutov - 2014-06-19

    Thanks for the patch. As the code is not licensed, and you added the patch to the public tracker, I will add the standard FindBugs GNU Lesser General Public header to the patch. OK?

    Regards,
    Andrey

     
  • Tagir Valeev

    Tagir Valeev - 2014-06-19

    Sure, no problems.

     
  • Andrey Loskutov

    Andrey Loskutov - 2014-06-19
    • status: open --> closed-fixed
     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

JavaScript is required for this form.





No, thanks