Code Indentation and Nesting. Ash Furrow on avoiding unnecessary code indentation:

Since first year when a sage upper year student showed me how to avoid unnecessary indentation in my code, it's something I've tried to do. I won't correct existing code since it doesn't improve performance, but I structure my code to avoid superfluous tabstops.

I have a similar habit, but it's not so much in the name of avoiding indentation as it is avoiding nesting. At first glance, the two appear to be similar (they commonly have an identical appearance, even). But the crucial difference, as is often the case with program writing, is semantic.

The greatest benefit of this style is bailing early. Instead of deeply nesting your code (and thus heavily indenting it), you have simple statements designed to end execution in as few instructions as possible, and designed to be as simple to follow as possible. Consider the examples:

- (void)doSomethingWithString:(NSString *)s { if (nil != s) { if ([s length] > 0) { NSLog(@"%@", s); } } } // VS - (void)doSomethingWithString:(NSString *)s { if (nil == s) return; if (![s length]) return; NSLog(@"%@", s); }

Astute readers will notice a few things:

My second example is actually longer than the first. My second example is more readable. Imagine there were 5 conditions I needed to check before I could execute the main section of the method. How ghastly would the nesting be in such a case? The nil and length checks, combined, are redundant in this particular example (because nil responds to messages by returning nil ie 0x0 ie 0 , calling [s length] would return 0 for both an empty or nil string). It's contrived but hopefully illustrative.

There is of course the whole other aspect of this particular “bailing early” style when it comes to memory management. Extra care must sometimes be taken if you adopt this style. That will sometimes mean using autorelease more frequently, or it might mean you repeating your release code in multiple places to avoid leaking allocated objects. This is rare in practice, I've found, but it is something to keep in mind.

Further reading by Wil Shipley.

Tuesday, May 17 2011