Number 25
May 15, 2024

Conjunctions in your functions

Most code and documentation style guides ask us to write brief descriptions of every method and function. In addition to the usual benefits of documenting our code, writing those descriptions helps us notice improvements we can make in it. For example, if a function’s description is hard to understand, its code is probably too complicated.

Two men looking at a paper scroll.—Goodness me! This function does so many things!
—You haven’t even seen the best part yet.

A rule I follow often is that if a function’s description contains the word “and” or the word “or,” it’s almost always necessary to split that function into several pieces. A function should do only one thing, not two or three, and the presence of a conjunction in its description hints that we are not following this rule.

Of course, the meaning of “only one thing” depends on your code’s level of abstraction. In one part of your program, one operation might be “calculate the sum of an array,” while in another part of the same program, it could be “build a profit and loss report.”

We often combine several operations in a single function to avoid duplicating code. Instead of writing two nearly identical functions, we write one function with a parameter that selects one operation or another. That is a mistake. The combined function’s code will always be more complex than two separate functions, and it will only become more complicated as time passes and we need to make changes to it.

Imagine a totally hypothetical program to send email newsletters with a function described as “schedule an email for later or send it immediately if the date is empty.” That “or” in the description tells us we should split it into two functions.

When I split it —I mean, should a hypothetical programmer split it— the result would be two nearly identical functions, except for the last line. This annoys many people, but luckily, the solution becomes evident when we describe both functions (“prepare an email draft and schedule it” and “prepare an email draft and send it immediately.”) As you can see, both descriptions contain the conjunction “and,” so we must split them again. In the end, we have three functions: “prepare an email draft,” “schedule a draft for sending,” and finally, “send a draft immediately.”

This hypothetical story that never happened to anyone you know started with one function and ended with three, but each function does only one operation, is smaller and easier to understand, and there is no code duplication.

Next time you add a parameter to choose one or another operation when you write a function, think again. Describe your function. Does it contain the conjunctions “and” or “or”? Should you split it into several simple functions instead of a single complicated one?

The illustration for this Coding Sheet comes from an engraving by 勝川春章 (Katsukawa Shunshō).