We all know that simpler is better when it comes to software
development. Any time there is code that
is overly complex it makes it hard to test/debug and it is much harder to interpret
in the future when changes/enhancements need to be made. There are a few different ways that
developers can attempt to keep their code simple. We can use techniques such as Functional Decomposition,
we can conduct code reviews, TDD, adopt pair programming, etc.
There is another way
we can attempt to keep our code simple.
We can measure our code based on the Cyclomatic Complexity
measurement. This is a software metric
that attempts to measure the ‘pathways’ through a method/module (read the wiki
for a better definition). [Google Search on Cyclomatic Complexity]
One way to measure
the Cyclomatic Complexity of your application is to use a existing tool. I have chosen to use a plugin for
Reflector by Lutz Roeder.
After you have
downloaded/installed the plug-in, fire up Relector (this assumes prior
knowledge of how to use Reflector) and load the assembly you wish to view.
In order to run the code
metrics you need to select the assembly from the tree view in Reflector then go
to Tools -> Code Metrics. This will
open up a new panel with the different possible assemblies to run the metrics
against. Check the one you want and
click the refresh icon in the tool bar.
This will run analysis for your assembly. When this is done, it will give a listing of
the results for each class. If you wish
to view the results on a per method level, simply change drop down to ‘Method
Metrics’ to refresh the list for methods.
You will now be able to sort the results any way you want. I like to sort by the CyclomaticComplexity
rating.
If you see methods
with a rating of 10 or higher you may want to spend a few minutes to see if
there is any way to improve this logic.
The goal would be to have no methods with a complexity of 50 or higher,
while having most of your methods have a complexity of 20 or less.
Complexity Threshold
Values
1 - 10: Simple Program, without much risk
11-20: More complex program, moderate risk
21-50: Complex program, high risk
> 50: Untestable program, very high risk
I like to spend a few minutes here and there to run this on
my applications in order to get a view of what is going on. Learning to
use this tool effectively will make your code base simpler, and your application
better. Both of these are keys to
success in the software world.
Enjoy…