This is in response to Greg Borenstein’s article titled A Beginner’s Guide to Practical Syntactic Magic: the tale of Hpricot’s sudo-constructor and Stuart Halloway’s follow-up article, With great power comes great responsibility.

Both articles make reference to the odd method-naming tricks used in Why The Lucky Stiff’s Hpricot library for parsing XML (commonly HTML). In light of those tricks, I have a question for you all…

Which of the following two snippets of code would you:

  • Prefer to read
  • Be inclined to write
This:
1
2
3
doc = Hpricot.parse(open('http://www.atnan.com'))
title = doc.at('title')
articles = doc.search('.entry')
Or this:
1
2
3
doc = Hpricot(open('http://www.atnan.com'))
title = doc % 'title'
articles = doc/'.entry'
I’m interested in hearing your feedback in the comments below :)

5 Responses to “Which Do You Prefer, And _Why?”

  1. mc Says:

    I’d prefer to read and write the first. It’s less arcane.

  2. Gerald Kaszuba Says:

    It is easy to understand the first if you have little or no idea of the syntax.

    As for writing, either are fine to write in. Personally I prefer to not use the shift key for coding, e.g. I use single quotes instead of double quotes whenever I can when I have a choice in the language I use.

  3. Nathaniel Talbott Says:

    I personally prefer the latter – I like a bit of cleverness with my API. And I’m a bona fide _why junky :-)

  4. Greg Says:

    Hey Nathan,

    Nice way of phrasing the question. I think that my preferences may be a lot like what you were expecting people to say: I’d rather read the former, but I’d rather write the latter. While the explicit use of “parse”, “at”, and “search” make the code clearer if you have no idea of what it’s doing (for example, if you’ve never heard of Hpricot and don’t know that it’s a library for parsing web pages), they add up to a bunch of extra typing and (in the case of “parse” at least) method name-remembering.

    For my purposes, I’ll take the trade. The slight loss of readability (which mostly just applies to total novices to the lib—when really what I care about when it comes to the readability of my code is how well my future self will be able to make sense of it and I’m pretty sure I’m not going to forget what Hpricot is for) is definitely worth the decrease in typing, especially with a task like parsing, which can be quite repetitive.

  5. Greg McIntyre Says:

    I prefer the former for both reading and writing. In terms of writing the code, the former may be more verbose but it’s also more in line with POLS, IMHO. I could conceivably guess there’s a method called “search” and how it works but I have buckley’s chance of guessing that I need to call the ’/’ operator.

    IMO, POLS rating is proportional to code readability.

Leave a Reply