Flattening Arrow Code

In general, if the functions are small and compact, you can avoid the type of nesting shown.

I think, if you can, try for one return point in a function. This will enable you to put 2 debug statements per function, one at the start marking the arguments passed in and one at the end marking the return value back to the caller.

If you passing objects as parameters, this becomes more difficult, but if the functions are small and compact and doing a small amount of work, this works out quite well.

Additionally, I think debug statements that are used in this fashion gives a developer a good roadmap of what the application is doing without being to0 obtrusive or flooding the code with many debug statements. If there are many debug statements inside of function, perhaps the function needs to be refactored into smaller parts to follow this coding methodology.

I usually allow the deployment team to turn on or off the debug statement with a configuration setting. That way, if something goes wrong, we can turn on debugging to see what is going on without having symbols or a debug build or stack traces. If things really become hairy, then we get out the big guns and get dump files, etc.

Another benefit is that I can turn on debugging locally and look at the trace file and verify all the unit tests ran properly by verifying the output from the debug listener if I’m adding in new code (methods, functions, etc.)

Schmoo: sometimes you might want to print internal state of the function that isn’t returned; temporary calculations and such. It helps if your function isn’t one-to-one.

My preferred method to flatten arrow code is to use the do-while-false loop like below.
Eg.

ReturnCode = false ;
do
{
if(!condition)
break ;

 if(!condition)
    break ;

 //do work
 
 ReturnCode = true ;

}while ( false ) ;

It has helped with increasing readability, the code stops execution immediately upon an error condition and single return point is also retained. But this tactic seems to be unpopular on the net but without any substantive reasons.

Jeff, do you think the do-while-false to be a coding horror ?

Housekeeping note: the cyclomatic complexity link is broken, and there doesn’t appear to be a replacement page at SEI. While I’m at it, the message under the “Post a comment” box is missing a space between sentences: “…style your text.URLs automatically linked.”

Many thanks for the tips Jeff - I’ve just come across a bunch of code which needed some attention. I duly used the tips on this article and if you’re interested take a look at the end result (http://www.matthewedmondson.info/2010/09/preventing-arrow-code.html)- I massively reduced the amount of branching and loops and its actually understandable now. Keep up the good work.

A name I found for structured programming techniques (especially single exit point) is “zombie practices”: http://interfacesdesign.blogspot.com/2011/05/single-exit-point.html