Archive for November, 2009

Forest and trees: code comprehension

Friday, November 6th, 2009 | Uncategorized | No Comments


Recently I was asked to investigate a piece of relatively old production code (one class actually), which started causing problems after some recent modifications. Unfortunately, the class in question had some… let’s say it was programmed by following not the best practices, which included mutable global states, static state modifiable from public static methods and very long methods. This made analysis of the code somewhat challenging and I’ve ended up refactoring it in order to reduce the state scope and its mutability.

There was one really long method consisting of 314 lines of code. This was not just a linear piece of code — it had many conditional operators resulting in cyclomatic complexity of value 44 (almost 42).

After finalising all required work to correct the reported problem I have sent an email to the team responsible for maintaining the class in question. This email addressed a matter of higher code quality with a special emphasis on facilitating code comprehension by avoiding global mutable state and reducing the size and cyclomatic complexity of methods.

Here is a snippet of the reply I have received:

Although advocating low code cyclomatic complexity, in the extreme case it is easier for a business analyst [code name for a person amongst other things also doing programming, 01es], especially one not intimately familiar with Java or the listener [a Java class, 01es] in question, to parse and understand a single method with 314 lines than 314 methods with 1 line each. Especially when debugging, where one long method can be traced in 314 steps, but many smaller methods cause jumping throughout the code causing distractions while trying to follow a (potentially simple) execution path.

I’d like the reader to ponder the above quote for a few seconds …

Forest and trees

Walking in the forest between the trees is wonderful… especially in Autumn when there are plenty of colourful leaves on the ground. However, walking between the trees won’t tell us how large is the forest or where does it have clearings. If one would like to comprehend these questions s/he needs to rise above the forest high in the sky — zoom out to see a more generic picture. Hovering above in the sky one could see the boundaries of the forest and clearings. If forest clearings are not visible very well then a slight descend could help — zoom in to see the necessary details. Having descended to the ground facilitates a close inspection of the trees again.

Hope that the forest and trees metaphor can easily be translated into the comprehension and debugging of the code. Don’t forget the stepover and stepin capabilities, which are featured in most modern debuggers.

Have a nice code comprehension experience,