Friday, October 24, 2008

How I Indent My Code

You get spaces for free. You might as well use them.

The style's unusual, as far as I can tell. Coming from some backgrounds, it may look very strange. Depending on your expectations, the last example is either completely insane or nicely separated into semantic components.

I get the style from Lisp. Note the long series of right-side parentheses, square brackets, and curly braces at the end of the last line of the last example, and the frequent clusters of right-side square brackets in the second example. Working with lists of lists requires this style if you want your code to be readable at all, and a lot of Rails and Ruby stuff has you building lists of lists, especially with keyword hashes.

The last example's an extreme example and valuable for that reason. This example makes it very clear what benefit the style gives you. The square in the upper left is a list of keyword arguments; the square in the lower right is a list of objects and their initialization keyword arguments. In either case, you're dealing with a long list of things, separated out into categories. All the keyword arguments are in the same square; all the new objects are in the same square. If there were more than one Mix object in that construct, they would both indent to the same margin, and there would be two of those right-hand side new object blocks.