Michiel de Mare

No Space For Bugs

In the previous article about maph and Enumerator#key, I didn't motivate why I believed that these methods, which add no functionality and purely allow code to be written slightly differently, are worthwhile. You can plot these different approaches on a chart. Somewhere to the left is the for-loop (when asked about adding functions like map, Rob Pike, the creator of Go, said "Just use a for-loop"). Then we have each or forEach with a block, then map itself, and then to the right is Ruby's symbol notation, select(&:even?). Finally, far to the right, there's Lisp.

Look at these fragments:

# 1) for loop
names = []
for h in users
  names.push(h["name"])
end

# 2) each
names = []
users.each {|h| names.push(h["name"]) }

# 3) map
names = users.map {|h| h["name"] }

# 4) maph
names = users.maph("name")

I would argue that the essential property that changes in these examples is not primarily code length. Nor is it readability, which is in the eye of the beholder; I bet there are many programmers that would argue that the for-loop is much more readable than the maph example.

What actually changes is that the examples are progressively less like code. Technically, of course, there is no difference. But I can refer to "the set of first names of my co-workers" without saying what they are or mentioning a procedure to enumerate them. And similarly, I can refer to users.maph("name"). It is a recipe for producing the names of these data structures with user data, but simultaneously, it is the thing itself.

Nor is there any space for bugs in users.maph("name"). Which is not to say that it does what you want - maybe name doesn't refer to the kind of name you need, maybe users contains User objects instead of hashes, maybe some of them are nil. So, yes, the "What" aspect may still be incorrect. But the "How" aspect is simply Not Interesting - there is nothing to debug, nothing to review.

In a way, the goal is to have a declarative language for basic operations on arrays and hashes, just like there is XPath for XML, selectors for CSS, and jq for JSON.