Abstracting Code By Building a ‘Vocabulary’

One of my frustrations as a front-end developer is the temptation to spend all my time learning tools instead of learning how to write better code. In order to counter this, lately I’ve started working my way through Eloquent Javascript while simultaneously trying to work my way through Structure and Interpretation of Computer Programs.

One reason why I’m reading SICP is that it was recommended to me as book that helps you learn to take really complicated problems and break them down into simpler components. The book itself admits this early on:

In general, computational objects may have very complex structures, and it would be extremely inconvenient to have to remember and repeat their details each time we want to use them. Indeed, complex programs are constructed by building, step by step, computational objects of increasing complexity… This feature encourages the incremental development and testing of programs and is largely responsible for the fact that a LISP program consists of a large number of relatively simple procedures.

Eloquent Javascript adds an interesting wrinkle. Not only is solving complex problems about distilling them into a series of simpler steps — it’s also about making those simple procedures correspond to the original problem (emphasis mine).

Let’s briefly go back to the final two example programs in the introduction. The first is self-contained and six lines long.
var total = 0, count = 1;
while (count <= 10) { total += count; count += 1;
}
The second relies on two external functions and is one line long.
sum(range(1, 10));
Which one is more likely to contain a bug?
If we count the size of the definitions of sum and range, the second program is also big — even bigger than the first. But still, I’d argue that it is more likely to be correct. It is more likely to be correct because the solution is expressed in a vocabulary that corresponds to the problem being solved. Summing a range of numbers isn’t about loops and counters. It is about ranges and sums.

I don’t have a concrete example yet, but approaching a complex problem by asking “What is the vocabulary I need to solve this?” feels like little light switches being flipped on in my brain, and I love that feeling.