Clojure Gazette 186: How Small Abstractions Help Beginners

Sign up for weekly Clojure tips, software design, and a Clojure coding challenge.


How Small Abstractions Help Beginners
Clojure Gazette
Issue 186 - August 15, 2016

Hi programmers of all types (pun intended),

Some beginners are beginners to programming in general. And some are beginners to our particular codebases. Either way, having lots of little named abstractions helps them learn the intent of the code. Small abstractions can decrease ramp-up time of new employees.

You see, there's no point in naming an abstraction as a description of how it works. The code itself says how it works. Here's an example:

(defn take-up-to-colon [s]
  (apply str (take-while #(not= \: %) s)))

The name just says exactly what the function does (and maybe less). So that's not really an abstraction. It's just a restatement of the same concrete idea. What you really want is a name that adds meaning, specifically some kind of intent:

(defn url-scheme [url]
  (apply str (take-while #(not= \: %) url)))

Oh! It's for getting the scheme part of a url! Now it's clear. Actually, a couple of things are clear.

1) When you should use this function.

Even though it may work to parse the string "name: Eric Normand" and extract the key with it, this is clearly not a URL so you shouldn't use the function.

2) How this function might change.

This is not a totally robust implementation of extracting the URL scheme. As you process more URLs, you may find that it's not sufficient and you'll want to improve it. But you still know that it will be intended for URLs and not general strings. The implementation might change, but the intent is constant.

It can be argued that this is just a one-liner and can be inlined. But you're missing out on all of those chances to give real meaning to your code. It's just data until you make it meaningful.

So, of course, a newbie to your code will love to read the meaningful names. They won't have trouble with the why questions. They'll be able to jump in more confidently and with less help. And we all know that we're all noobs after two weeks of not reading our own code.

Unfortunately, everything I've said here is purely based on anecdotes and speculation. I'd love for someone to test this empirically. We really need more solid, evidence-based research around how best to organize our code.

Rock on!
Eric Normand <eric@lispcast.com>

PS Want to get this in your email? Subscribe!
PPS Want to advertise to smart and talented Clojure devs?