Saturday 29 November 2014

Why he vertically aligns his code (And why you shouldn't)

Over on Terence Eden's blog, the latest post is about vertically aligning code : https://shkspr.mobi/blog/2014/11/why-i-vertically-align-my-code-and-you-should-too

The "bad" example looks like this:

Which is then "fixed" to make it look like this :


Just for comparison, I typed it into my regular text editor:


The point being, because I'm using a well designed syntax highlighting where the numbers (green) contrast with the operators.  If you so choose, you can visually inspect just the green numbers and just as easily spot the outlier.

(Pro-tip: To concentrate on just one color, defocus your eyes slightly by staring "through" the plane of the monitor to engage your eye's cone cells.  With a little practice, you'll find yourself doing this automatically when you want to focus on the structure of the code instead of the details.  For best results, you might need to make the glyphs larger on screen....)

Note too, how the combination of proportional font and camelCase instead of under_scores keep the code density onscreen the same, but the individual glyphs appear larger in-place.

My code editor also uses syntax highlighting to hint the kerning.  So for example, the kerning around the equals sign and the semi-colon are particularly loose to aid in their recognition. Similarly, the single space character (' ')  has a width 50% larger than would be used for normal paragraph text.

But here's the big change that Terence missed, I've sorted all the variable declarations alphabetically to ensure there are no duplicates.  This is a zero-cost policy that can simplify merges and conflict resolution when multiple variables (possibly duplicate) have been added upstream.

Coding Atoms

The bigger problem is the coding atom is the line-of-code.

Lets take another code example from Terence's blog post, this time a function declaration :

extern int SomeDemoCode(int fred,
                        int wilma);

That's an atom right there - you can't split that up without changing its meaning. Watch what happens if I try to add a parameter in an excess white-space environment:

extern int SomeDemoCode(int fred,
+                       int barney,
                        int wilma);

The diff splits our (atomic) function signature across 3 lines, exposing us to problems where a git merge might accidentally succeed, when really we need it to flag a merge conflict.

(For a real world case of how bad automatic merging can be, take a look at the Goto Fail Bug)

Now compare if everything had been on the same line, the diff would look like :

-extern int SomeDemoCode(int fred, int wilma);
+extern int SomeDemoCode(int fred, int barney, int wilma);


TL;DR: Using whitespace to control your code presentation is a hack from the '70s.. get a better editor.

p.s. Some formatting edits have been made to make this post clearer.