Monday, April 03, 2006

Blowing Your Mind

In pursuit of code quality: Monitoring cyclomatic complexity "This report's section labeled Top 30 functions containing the most NCSS details the largest methods in the code base, which incidentally almost always correlate to methods containing the highest cyclomatic complexity. For instance, the report lists the class DBInsertQueue's updatePCensus() method as having a noncommenting line count of 283 and a cyclomatic complexity (labeled as CCN) of 114.

As demonstrated above, cyclomatic complexity is a good indicator of code complexity; moreover, it's an excellent barometer for developer testing. A good rule of thumb is to create a number of test cases equal to the cyclomatic complexity value of the code being tested. In the case of the updatePCensus() method seen in Figure 2, you would need 114 test cases to achieve full coverage."

"Because cyclomatic complexity is such a good indicator of code complexity, there is a strong relationship between test-driven development and low CC values. When tests are written often (note, I'm not implying first), developers have the tendency to write uncomplicated code because complicated code is hard to test. If you find that you're having difficulty writing a test, it's a red flag that the code under test may be complex. The short "code, test, code, test" cycle of TDD invites refactoring in these cases, which continually drives the development of uncomplex code."
Post a Comment