How crappy is your Java code? Often we find others code crappier than ours, especially if we are given to maintain their code. Crappy code authors are almost always happy with their code quality. Can we quantify crappiness?

Crap4J claims to be able to quantify crappiness in Java code with a simple formula (applicable to a method):
CRAP(m) = comp(m)^2 * (1 – cov(m)/100)^3 + comp(m)

Where comp(m) is the cyclomatic complexity of method m, and cov(m) is the test code coverage provided by automated tests (e.g. JUnit tests, not manual QA). Cyclomatic complexity is a well-known and widely used metric and it’s calculated as one plus the number of unique decisions in the method. For code coverage we use basis path coverage. Low CRAP numbers indicate code with relatively low change and maintenance risk – because it’s not too complex and/or it’s well-protected by automated and repeatable tests. High CRAP numbers indicate code that’s risky to change because of a hazardous combination of high complexity and low, or no, automated test coverage.

Generally speaking, you can lower your CRAP score either by adding automated tests or by refactoring to reduce complexity.

Now you can go to your boss and quantitatively show him that your code is less crappier than your colleague*. After all managers like numbers, even if they have crappy & dubious validity.

*Remember to forget that Crap4J even exists, or discount it heavily at any mention, if your code turns out to be crappier than your competitor.

Note: CRAP stands for Change Risk Anti-Patterns according to their definition.

Crap4J comes as an Eclipse plugin and can also be integrated with Ant. Check the video for a nice demonstration. The authors decided to use 30 as a threshold for crappiness.

I partially agree with the idea but I am not comfortable with the formula. Also it ignores cross-method complexity introduced and complexity of a class as a whole which may not always be the sum of the complexity of the methods.