Arrow Code

Here’s a good litmus test to determine how seasoned a developer is: ask him to design a method that is conditional clause heavy. Most developers will instinctively resort to arrow code: the excessive nesting of conditional clauses which pushes the code out into an arrow formation. Coding Horror has a good rundown of the problem and some tips to minimize it.

And you know you’re definitely in trouble when the code you’re reading is regularly exceeding the right margin on a typical 1280×1024 display

Guard clause is the most important concept to mitigate arrow code. Most developers are unaware how important it is. First, as explained in the article, it minimize convoluted conditional clauses (cyclomatic complexity). Since they act as sentry points, you can make sure that parameters are satisfied first before moving to the next line of code. Succeeding code can execute with a privilege that variables will always be present, no checks needed (thus reducing additional conditional clauses). Second, it creates a clean and elegant method anatomy: guard clauses, purpose of the method, and return. This makes the method self-documenting and predictable. This also allows you to plan usage of resources, which brings me to my third and last point: efficiency. Resources will only be spent when they are actually needed.