Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Jim Plush's Blog:
Cyclomatic Complexity for the Test Driven PHP'er
Jun 05, 2006 @ 19:45:55

Unit testing in PHP applications is growing more and more in popularity, so much so that some developers get into it, test all of their code and aren't exactly sure when enough is enough. Jim Plush has a suggestion for those kinds of testers - consider the cyclomatic complexity.

It's one of the most common questions you ask when you first start using Test Driven Development or Unit Testing in general... When am I done?

It's the point you feel confident when all your tests exercise the code in your classes. How do I know when that point is? I've come across a new way of finding this point using something called cyclomatic complexity. Developed by Thomas McCabe in the 70's cyclomatic complexity is a simple measurement of how complex a piece of code is. One of the nice parts of it is that you can use it when working with unit tests.

To illustrate, he gives a simple example of a function with only a function call and return inside. This has a cyclomatic complexity rating of 1 (the lowest). Now, start adding in ifs, loops, and other ways for the data to go and you start adding more complexity levels. Jim suggests that this can be another useful unit testing measurement - one more unit test for each level of complexity.

He also notes a pleasant side effect of this sort of classification:

The other nice part of a CC number is you can quickly find out when a method is ripe for refactoring. If you have a method with a CC number of 20 you know you most likely have a problem on your hand.
tagged: cyclomatic complexity unit testing levels refactoring cyclomatic complexity unit testing levels refactoring

Link:


Trending Topics: