The only difference between coding styles and religion discussions is that coding styles have claimed fewer victims—at least until now. A few post back I discussed color schemes, and this week I’ll be discussing code geometry for enhanced clarity.
A few days back I was discussing with a friend whether or not comments in code should be rather narrow, spread vertically in short lines, or if they rather should be “line long”, that is, about 70 or so, characters wide. He agreed that short comments broken in many lines are easier to read than very long lines. A coworker came to the opposite conclusion: short, broken comments were “stocky”. Of course, like other style matters, that is ultimately to everyone’s own taste; but I wasn’t sure why I found them much easier to read.
My personal theory is that eye movement is minimized with short lines. There’s a certain vision angle in which we seem to be able to just grab a bunch of letters without really scanning them. This angle is not very wide—maybe 5°—and very long lines forces us to scan text jumping over every few words. That’s probably why newspaper, blog templates, and scientific journal all use multiple and rather narrow columns: one can read while essentially scanning the text downward only.
Let us look a piece of code I wrote recently (what it does is somewhat irrelevant right now; let’s say it’s an extra goodie). In my default EMACS view (80×60-something) the code appears:
Using GIMP I illustrated (“artist conception”) the path my eyes take when I read the text:
Now, what would it look like if I used long lines instead? The code would now look like this:
and I suppose my eyes would scan the text like this:
So I think I may improve code legibility quite a lot just by keeping moderately short lines for comments and code. This also implies that indentation must also remain rather shallow—except possibly for Python. Tabs that are 4 space wide now seems too long and indentation too deep. I use a 1 or 2 space variable width tab, as you can see from the above screenshots (I spent some time to tweak EMACS’s CC mode to get that particular setting).
Bonus technique for EMACSers: the fill-paragraph-function packs text in a mode-dependant way using the variable fill-column that delimits the maximum number of columns in a line. It is bound to M-q by default. Pressing M-q will cause a paragraph to pack itself in lines of at most fill-column characters. It also behaves correctly in most modes (it understands comments).