Why I vertically align my code (and you should too!)


There was an interesting discussion on HackerNews last week about the Linux Kernel coding style.

During the discussion, I kicked off a minor holy war about whether one should vertically align code. I'm all for it! Let me explain why.

What Is Vertical Alignment?

Take this trivial example:

int robert_age = 32;
int annalouise_age = 25;
int bob_age = 250;
int dorothy_age = 56;

I find easier to read as:

int robert_age     = 32;
int annalouise_age = 25;
int bob_age        = 250;
int dorothy_age    = 56;

At a glance I can see that "bob_age" is unusual. I can easily see that everything there is an integer without having to slide my eyes around.

This view is not universally shared - so I shall attempt to explain why many people think it is a useful style guide.

Comprehension

90% of programming is problem solving. The other 90% is understanding how the problem was solved.

Reading code isn't much different from reading prose. We expect authors to explain their arguments clearly, not be overly verbose in their extraneous use of their chosen language, and 2 respect da common grmmatcal style.

Indeed, the Kernel coding style emphasises this heavily. How you choose a variable name is as important as what the code does.

Consider the following line of code:

var thinG=doIt(thestuff,MORE_sTuff); /* LOL! */

Even if you deeply understood the codebase, that's not a particularly readable line of code.

var totalBill = apply_tax(initialBill, taxRate);

With a sensible application of naming conventions, spacing, and capitalisation, we've made the code much easier to read. That means the poor sap who inherits our code will spend less time deciphering it and more time understanding it.

Why Use Monospace Fonts?

As with all good old-fashioned flamewars, there are two equally passionate sides on the monospace vs proportional font debate.

Some heretical scum will tell you that proportional fonts are the best - ignore these heathens.
Others will sow your mind with discord as they argue for the eugenic purity of proportional fonts - those poor condemned souls.

Ultimately, it comes down to readability. What do you find easiest to aid your comprehension of the code? It's why IDEs have colour schemes - so you can tell at a glance whether "foo" is a function, a constant, a variable, or a comment. Anything which makes it quicker for you to comprehend what a block of code does is a good thing!

This is one of the reasons spreadsheets are so popular. Columns aid readability. You can quickly scan your eyes down a column and notice if a row is significantly different to its siblings.

We Don't Have The Tools

Interestingly, the big criticism I faced in the HN discussion was not about whether vertical alignment is useful - but around how poor our tools are.

This ruins the readability and usability of your diffs. Say you need to quickly track down a major bug due to a change in a single constant. With horizontal alignment, the diff might contain any number of changed lines, obscuring the crucial change. There are workarounds that ignore whitespace and word-based diffs, but it's just not worth the trouble IMHO.
Andreas van Cranenburgh

...And...

If you have, say, 50 lines of assignment and you align all the values to the largest one, adding one forces you to update 50 lines. I've been faced with those very situations and that is when I understood how important it is not to align values like that.
scrollaway

Those arguments are valid - in certain contexts - but point to the need for better tooling.

I'm reminded of the idea of Elastic Tabstops - a method to auto align code blocks:

By Nick Gravgaard
By Nick Gravgaard

Our tools can easily accommodate this way of working. Computers are there to do boring and repetitive jobs for us - and CPU cycles are cheap enough to "waste" on making our code more readable.

There are plenty of examples in the Linux Kernel where vertical alignment is used to make code easier for humans to parse.

Vertical alignment doesn't work in every context - but for quickly assessing data, its readability is unparalleled.

Coding is a creative medium through which we express our ideas. If our tools make understanding those ideas more difficult, it's the tools which need to change - not us.

26 thoughts on “Why I vertically align my code (and you should too!)

  1. I like vertical alignment too, but the two criticisms you mention (it wrecks diffs and we don't have tools) are valid points that suggest what's needed is a presentation mode, like syntax coloring, that does not modify source. That, I would use.

  2. The problem is -- tracking a line across a sea of whitespace is terrible. This is why tables of data alternate the colors of rows, because when your eye leaves the "left column" and goes across the sea of whitespace to the "right column" it is exceptionally easy to get lost, and read the WRONG value... and now you have a far worse problem. The smaller the font, and the more values you have -- the worse the problem gets... try an example with 50 values and a diversity of lengths from 5 chars to 25...

    1. I think alternating the row color was a design fad instigated by Apple a number of years ago (OS9 maybe? or an early version of OSX?). It's not a bad solution, but it's not exactly traditional either.

      A more traditional solution is to make the whitespace visible; a row of periods is a very common choice. They don't need to exist in the source, visualizing the whitespace characters is already something most editors can do.

      1. As usual, Apple may have popularized it (although even that is debatable), but they didn't invent it. Tractor-feed line printers have used paper with alternating line colour for decades.

    1. Using simple diffs for actual coding (as opposed to documentation or machine readable) is a hack from the 70s too. You talk about an awesome editor capability then justify a choice on your absolute abomination of a diff tool. Vertical alignment is awesome and having an actually modern tool chain is too.

  3. I'm 100% with you! The '50 lines of assignment' argument is a straw man argument. The next generation of diff tools will have a much better semantic understanding of code and so whitespace will have no bearing on diffs.

  4. I TOTALLY agree with this approach I do it for the purose of signal-to-noise ratio. If the equal signs are all aligned, then I can focus on exactly what is different. If the equal signs are not aligned, then I have to wade through all of the lines to just see the differences. I do this in Java and all of my original development is done this way. It's tremendously valuable. I am so delighted to see this piece here. Thank you!!!

  5. Copying and pasting this from a comment I left on a separate HN post:

    It takes longer to read a line of text that has more whitespace than it does to read a line of text with less whitespace and proper syntax highlighting.
    In addition to this, modern typography has different rules for different mediums. Bringhurst's typographic styles weren't meant to be applied to C# code nor should they be. We don't read code the same way we read books or magazines, thus it doesn't need the same treatment.
    If we are going to start applying modern typographic elements to code that we write, then we need to start thinking about incorporating various font faces, weights, worry about the kerning and leading, add some headers and a host of other things.

  6. Thanks for fighting the good fight.

    I think good code shares a lot of features with good writing. Writers should not just carry the reader through a cogent argument (which is a formal process with explicit rules much like a computer program), but also should clearly use language, and anticipate (and account for) a reader's prejudices and expectations from the author. If you have extra time (and are quite adept) you also might be able to fit in having the reader like and identify with you personally, but this usually comes from being a careful master of all other aspects of the craft instead of making any direct appeal.

  7. Oh please, if you just get a decent editor that can understand syntax and display various components differently (changing colors, etc), you won't have to worry about wasting your time putting in spaces. Example for windows: Komodo. There are many others. Just get a better editor! What's next? Putting in extra spaces in your file names??

    1. Here is an example of real life Python code. Lines 41 – 46 are vertically aligned, lines 48 – 53 are not. I find lines 48 – 53 easier to decipher with a glance, whereas the vertically aligned variables seem to get lost within the conditional statements.

      https://i.imgur.com/0afcuYU.png

  8. Maybe it's your tool that is poor. Your editor could probably align your code automatically without adding useless whitespaces to the source file. Everybody would be happy.

  9. Just noticed this old post, but will comment anyway in case anyone still reads it. Been vertically aligning code for 30 years... Helps a lot, especially spotting missing code like commas or semicolons. Even good syntax editors just tend to colour a whole block red or underline rather than spot the exact problem like the Number One Eyeball can. Each to his/her own and ban all style checkers is my view. I once formatted a piece of code beautifully. A style checker then reformatted it automatically into alphabet soup when I checked it in. Well if that's what folk want, they get it. My favourite would be a minimizer like for js on checking in - removing all white text not absolutely necessary for compilation. On checking out again, the pretty printer would format it according to whatever the next guru thought cool. And then minimize it back again on the next check in. That way everybody is happy.

What do you reckon?