23 January 2012

Why do we indent code?

Apparently one of the rules of Stack Overflow is that if enough people read and like a post, it gets deleted. Here is one of mine from two years ago. For a time, it was my top-voted answer.


Q: The firm where I work has programmers who still don't seem to understand the importance of indentation and write all the code aligned to left margin. What arguments can I put to convince them of the importance of indentation? —Phulore R, 16 Feb 2010


A: Clearly we’ve all internalized this so much that no one can remember why we do it. At least, none of the other answers so far. ;)


Why is indentation so useful? Because control flow jumps around in a program, and indentation helps you find where it's going. For example:


if (k == 0) {
if (!foo.hasKey(bar))
foo.put(bar, 1);
if (order.held())
order.release();
else
order.markUpdated();
}
Notifications n = order.getNotifications();
if (n != null)
n.sendUpdate();

On the first line, what if k isn't zero? Where do we jump to?


With indented code, you can just visually scan down to the next bit of code directly underneath the if:


if (k == 0) {
    if (!foo.hasKey(bar))
        foo.put(bar, 1);
    if (order.held())
        order.release();
    else
        order.markUpdated();
} //<---- here!
Notifications n = order.getNotifications();
if (n != null)
    n.sendUpdate();

Similarly, at the end of an if block, indentation helps you visually skip over the else block. And at the end of a loop, your eyes can easily zip back up to the top.


Once you're used to it, you can easily follow a break or continue.


Persuading people of anything is hit-or-miss no matter how right you are. :) It seems like it would be best to try to convince one person at a time, in a totally non-confrontational way, using respectful language and real-world examples.


I hope you can convince your colleagues to use indentation, but if not, remember they are human beings doing what works best for them. And remember they’re your teammates. Treat them humanely. Write code they can work with. If you like, spin yourself a little emacs mode that auto-indents the file when you open it and un-indents it when you save it. It’ll be fun, and you’ll have a story to tell. Life is too short to spend it bickering over stuff like this.


No comments: