An oft-uttered mantra in programming is to write "good" code that is well-organized and understandable. One obvious question is how do you know if you have "bad" code that is too complicated and unintelligible?
People have researched this question and have come up with "complexity metrics" to quantify how complicated a piece of code is. A well-known metric is the McCabe complexity metric or "cyclomatic complexity." It roughly counts how many different paths you can take to get from the beginning to the end of the code. The more branching statements and loops in the code, the more complicated it is. A rule of thumb is that a module should have a cyclomatic complexity of no more than ten (CC < 10). If the cyclomatic complexity is larger, you should refactor the code.
This is really cool. It's great to have a non-human, automated method to test the complexity of code. I'll have to try running some complexity metric tools on the next programs I write.
For further reading, check out Reg. Charney's article on code complexity metrics in Linux Journal or this IBM development article on cyclomatic complexity.
No comments:
Post a Comment