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.


Share this post on…

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

  1. xcode says:

    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.

    Reply
    1. George says:

      Xcode:

      Oh Please.

      Vi has been able to handle vertical alignment of code since the 1970''s.

      We have always had the tools.

      Reply
  2. RobertMeta says:

    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...

    Reply
    1. says:

      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.

      Reply
      1. says:

        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.

        Reply
  3. Andrew says:

    I had never heard of the 90-90 rule before. I now plan to overuse it until somebody slaps me. Thank you good sir.

    Reply
  4. 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.

    Reply
    1. OS X 10.10 user here — the "-b" switch to diff is described as "Ignore changes in the amount of white space". The tools are already in place.

      Reply
    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.

      Reply
  5. says:

    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!!!

    Reply
  6. I agree with this approach, with the use of modern editors and plugins one can easily get the variable assignments auto arranged without any waste of time.

    Reply
  7. robotkilla says:

    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.

    Reply
  8. says:

    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.

    Reply
  9. says:

    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??

    Reply
    1. robotkilla says:

      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

      Reply
      1. says:

        I'm all for vertical alignment but not in the case like is shown in the image with that big long space. Vertical alignment is a style but let's net exaggerate. I use it when it makes sense.

        Reply
  10. mike says:

    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.

    Reply
  11. FM says:

    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.

    Reply
  12. Rico says:

    This "Old" way to align code gets real ugly real fast in maintenance. I mostly hate aligned function parameters.

    Here is a partial quote from "Clean Code" by Robert C. Martin - ch.5 Formatting - Horizontal Alignment - p.87 (I changed my mind after reading and applying this in real life) :

    "...this kind of alignment is not useful. The alignment seems to
    emphasize the wrong things and leads my eye away from the true intent. For example, in
    the list of declarations above you are tempted to read down the list of variable names without
    looking at their types. Likewise, in the list of assignment statements you are tempted to
    look down the list of rvalues without ever seeing the assignment operator. To make matters
    worse, automatic reformatting tools usually eliminate this kind of alignment.
    So, in the end, I don’t do this kind of thing anymore. Nowadays I prefer unaligned
    declarations and assignments, as shown below, because they point out an important deficiency.
    If I have long lists that need to be aligned, the problem is the length of the lists, not
    the lack of alignment."
    I strongly recommend reading the entire chapter. An eye opener on this.

    Reply
  13. JK says:

    I do vertical alignment, but only indention on the left. I want to add one more point why i hate "=" alignment. I prefer small screen that allows me to work anywhere. This is a strong reason for me to use non-monospace fonts because non-monospace fonts save space horizontally so i can see more code in one line. Another less strong reason is that i simply like hand-writing style, only personal taste, please my eyes while coding. Just try to change to a non-monospace font and read a "=" aligned code, that effort of "alignment" is so effort in vain.
    Even i know from students time we are asked to use mono-space fonts for coding. But time changes, there are syntax color highlight, much better than wasting too much space for "alignment". This is no longer a hard rule. No company I know that regulate developer to use certain fonts... That is more like a job for UX to design customer facing UI. Use which font is a personal taste.

    IMHO, left indention is more than enough. Code are formulated well in any IDE with any font setting.

    Reply

Trackbacks and Pingbacks

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> <p> <br> <img src="" alt="" title="" srcset="">