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.

19 comments:

  1. You bent over backwards to find a irrelevant example. Placing method parameters like you have here is not the same thing.

    Also, you syntax-highlighter is a non-sequitir. You are side-stepping the value his solution provides.

    It's in essence a question of Signal-to-noise ratio. When you just pile your code together as in the "bad" example and your regular text editor with syntax highlighting, you hide the signal in the noise. When the equal signs are aligned, it allows follow-on developers to instantly focus on the signal.

    In both the "bad" example and your alleged improvement (the color is an improvement but it does not negate the badness of the lack of alignment) you force follow on develpers to extricate the signal from your noise. So, the entire point of this post is moot and wrong.

    ReplyDelete
    Replies
    1. Hey Tom!

      Both my examples are straight out of Terence's blog.

      I've updated the body to make that a little clearer.

      --C.

      Delete
    2. You also mention the Signal-to-noise ratio. I wish I had more space, but in a nutshell, the most important signal in the code is the variable names and function calls. My editor reserves the highest contrasting pair, yellow-on-black, to help that signal shine through.

      You clearly seem passionate about this issue, why not send me an email / tweet and I can walk you through some of my thinking...

      Delete
  2. Please take a minute to understand apostrophes. In particular, "it's" is not possessive. For example you say "without changing it's meaning". The apostrophe here is completely wrong.

    ReplyDelete
    Replies
    1. Good spotting! Fixed :D Thank you!

      Delete
    2. Thanks for making the correction. Now if only Terence Eden would correct his mistake of calling horizontal alignment "vertical", then we'd really be making progress.

      https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.6.3-horizontal-alignment

      Google Java Style

      4.6.3 Horizontal alignment: never required

      Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
      This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.

      Here is an example without alignment, then using alignment:

      private int x; // this is fine private Color color; // this too
      private int x; // permitted, but future edits private Color color; // may leave it unaligned

      Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a "blast radius." This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.

      Delete
    3. I have never seen alignment described the way you use it, only ever as the axis to which the elements are aligned. In this case, it is a vertical axis.

      Delete
    4. Lol, that's Terence's term, not mine! Take it up with him :D

      Delete
  3. How did you manage to create a disconnected diff output like that? Universal diffs per default keep enough context to inspect single-line insertions.

    ReplyDelete
    Replies
    1. Sorry for the confusion, is the article clearer now?

      *Edit : An earlier version of the article featured a hastily prepared disconnected diff output which has since been fixed.

      Delete
  4. Your comment about getting a better editor / IDE is understandable. However, regarding the single line diffs is ridiculous. All diff tools I've ever used always show the diff in context which means it'll display a few lines above and below the change so you'll never see just a single insertion, modification or deletion on its own.

    ReplyDelete
  5. You say to us get a better editor. I say to you get a better diff tool.

    ReplyDelete
  6. 1) What is this editor you are so lyrical about?

    2) This: http://nickgravgaard.com/elastictabstops/

    ReplyDelete
  7. I would argue that your rebuttal is pure madness. diffs don't look like that in the real world and they absolutely look better lined up. However, I gave up aligning stuff a couple of years ago as the kids these days rely on the IDE reformatting tool way to much, making my formatting irrelevant. Now get off my lawn

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. You should use monospaced fonts in your oh-so-cool text editor.

    ReplyDelete
    Replies
    1. Hi John! Welcome!

      I'm open to that possibility. But you may be surprised to learn that I already use both proportional and monospace fonts when editing code, depending on which window I happen to have open at any given time.

      Why do you think I should use monospace fonts exclusively?

      Delete
  10. I actually thought you have a point until I got to the part where you said you like camelCase and proportional fonts for code. We already have glasses-mode in emacs to fix the camelCase eye-cancer, maybe we should just enhance it to properly align assignments. Then we have the best of both: a readable presentation and meaningful diffs.

    ReplyDelete
  11. I think you could mentally parse color coded + aligned code faster than simply color coded. I think someone should do a psychological study of this. Wouldn't be hard.

    Your method of alphabetically sorting however is really awesome. I will implement that.

    ReplyDelete