Code Virtues, part 2: Simplicity

Make everything as simple as possible, but not simpler.
Albert Einstein

Continuing in our discussion of virtuous (as opposed to beautiful) code, we come to Simplicity. Like correctness, simplicity is a special sort of virtue. We might call correctness the essential virtue, in that code that fails to be correct cannot be considered virtuous. Simplicity, on the other hand, is more of a meta virtue - it makes other virtues easier to achieve.

We’ll be looking at these virtues in detail in later posts, but think about comprehensibility and testability. Simple code is (almost by definition) much easier to understand than complicated code, and certainly takes less time to grasp. At the same time, simple code is also generally easier to test than complicated code - it’s easier to figure out how to test something with fewer moving parts.

Simple code is, fortunately, easier to write than complicated code. Test-driven development is an easy way to get started - you always write the simplest code that could satisfy your test, creating your software by the gradual accretion of these simple units. Of course, even that process could yield enormously complicated results, so you intersperse the creation of new code with bouts of refactoring to reduce the overall complexity of the system - simplicity is a virtue to be sought at all levels of development, from the smallest unit to the highest-level view of the application.

As with most of the other virtues (except correctness), however, there is a danger inherent in striving for simplicity in our code. As Einstein warns above, we must be wary of oversimplifying our code, reducing the complexity to such a point that our code becomes less correct - by failing to handle edge cases, for example. As is often the case, though, the other virtues may help guard against overemphasis on a single virtue. In the example just mentioned, we may avoid oversimplification if our code is testable - we’d know instantly if we removed something essential to an edge case when our tests failed.

Next time, we’ll talk about a virtue closely related to simplicity: comprehensibility.

Leave a Reply