Source Code Typography

When you run a blog such as this one you usually learn to live with writers block or you quit early. Or perhaps not “writers block” itself but just lack of good ideas for blog posts. My usual way of dealing with it is to go trawling the web for inspiration. When you stay cooped inside your own head for a while you sort of get into a self referential funk that might be hard to break out of unless you get some fresh perspectives and ideas from the outside. So I usually hit programming subs on Reddit, Hacker News and/or my RSS feeds to see if I can get excited about something enough to get a blog post of two out of it.

The side effect of such a fishing expedition is that you sometimes find blog posts that are exactly up your alley, but which tackle the subject so well that they leave precious little for you to add to. So then you are left with a choice of either linking to said block and saying “I agree with what that guy said” or blatantly plagiarizing it and hoping no one finds out. The other day I stumbled onto just that kind of article: one that I would love to have written.

The funny thing is that a lot of the ideas in that post were sort of in the back of my mind lately. I have been doing a lot of thinking about code readability, formatting rules and style guidelines for a lot of languages. I have been doing a lot of jumping around between PHP, Python and Ruby lately and I’ve been noticing how each of these languages approaches code style. Python for example strictly enforces proper indentation by making it part of the language syntax, coercing you to write code certain way. This of course doesn’t mean you can’t write atrocious python code, but it is generally harder to do than with say PHP.

The way code is presented definitely impacts it’s readability. I’m not just talking about the usual code guidelines such as using descriptive variable names and structuring your code the right way. I’m talking about purely aesthetic properties of code: consistent indentation style, short line length, alignment of elements in declarative blocks and etc.. go a long way in making the code easier to digest understand. This is the gist of the argument put forth in Dave Copeland’s recent Source Code Typography post: the way you indent and align your code matters.

For the lazy, let me re-use one of his examples: a snippet of a pretty common code you could find in a Ruby on Rails application:

def text_field_tag(name, value = nil, options = {})
  tag :input, { :type => "text", :name => name, :id => sanitize_to_id(name), :value => value }.update(options.stringify_keys)
end

This is fairly concise, albeit ugly code that scrolls off the page in most editors. Unless you have a decent sized screen you can’t actually look at the whole line without scrolling – and even then the length of it makes it impossible to figure out what is going on here at a glance. Dave argues that a very simple re-formatting can drastically increase the readability of the above code:

def text_field_tag(name, value = nil, options = {})
  tag :input,
      {
           :type  => "text",
           :name  => name,
           :id    => sanitize_to_id(name),
           :value => value

      }.update(options.stringify_keys)
end

I’m not going to re-iterate the entire post here – I recommend you just go and read it yourself. Dave makes some excellent points, especially with regards to the annoying leading comma convention that has become fashionable in the JavaScript community lately. What I want to do is add to his article by pointing out that there are tools you can use to make formatting code easier.

For example, to keep your code lines relatively short it is a good idea to set up your editor or IDE to highlight column 80 giving you a visual indication as to how wide your code ought to be. This provides a soft boundary that you can go over if needed. In Vim this can be done via a single line added to your .vimrc:

hilight ColorColumn guibg=lightyellow ctermbg=227

You can of course substitute lightyellow and 227 to your choice of colors – I picked these because light yellow goes well with my Solarized Light theme: it is visible, distinct but not too jarring:

Column 80

Column 80 Highlighted

Similarly, when you need to re-align some code (as in the example above) there exist two plugins that will do the job for you: Vim-Align and Vim-Tabular. The later is the newer, more feature rich plugin and there is an excellent Vimcast on it that you can watch here. Both essentially help you align blocks of code based on some sort of a token. They make a task that can be quite labor intensive (a lot of moving around and tabbing) into a two step process: select block to be aligned, then issue the alignment command such as:

" tabular.vim
:Tab /=>

" align.vim
:Align =>

In both cases alignment is usually done while respecting your tabs/spaces settings ensuring that things don’t completely break apart next time you re-tab your file (using g g = G).

How do you ensure that your code is optimized of maximum readability? Do you have any plugins or tricks for your favorite text editor you would like to share? Let us know in the comments.

This entry was posted in Uncategorized. Bookmark the permalink.



3 Responses to Source Code Typography

  1. Janek Warchoł POLAND Mozilla Firefox Ubuntu Linux says:

    Hi,

    interesting post – i’m into typography myself, albeit on a quite different field: musical scores. Here’s a short example comparing good and bad music typography – https://www.dropbox.com/s/cdlezke0assaiua/por%C3%B3wnanie%20sk%C5%82ad u%20nut.pdf
    I can translate the description if you want – is anyone interested?

    Reply  |  Quote
  2. FX FRANCE Google Chrome Mac OS says:

    I have tons, literally tons of comments in my code. Sometimes I have one comment for each line of code, but my usual ratio is close to 3 or 4 lines of code for 1 comment.

    I can scan code more quickly by skimming through lines of comments rather than actual code, and even seemingly completely useless comments (such as “increment such variable”) actually help me read faster and structure the code better than just letting obvious lines of code alone.

    I use Vim’s gq command intensively as well, but aside from that, the Syntastic plugin (I think I learned about it from one of your articles by the way!) uses PEP8 for Python, which is again highly useful!

    Reply  |  Quote
  3. JohnM17 UNITED KINGDOM Google Chrome Windows says:

    I’m absolutely in agreement with the idea of keeping one’s code well-formed, and have a particular thing for clear and consistent indentation and spacing. I also have my pet hates, one of which is this:

    function somefunc() {

    }

    which I insist should be done as:

    function somefunc()
    {

    }

    I’ve gotten into the habit when web-scripting to remove all unnecessary spaces after I’ve finished coding, in order to minimise file sizes and optimize loading performance of web pages. To this end I also use find-and-replace to change the names of variables, files and directories to single-letter designations prior to upload.

    Reply  |  Quote

Leave a Reply

Your email address will not be published. Required fields are marked *