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++:
According to their experience, explicit usage of PI constant is quite common:
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!
Log in to post a comment.