The word "elegant" is often employed flippantly to describe a particular class of software solution. Finding a software design book that doesn't use the term is challenging. Here are just a few examples:
- "Modify the code and the test to make it clear, expressive, elegant, and more general." - Modern Software Engineering by David Farley
- "The Unix system is a fine example of a powerful whole built out of simple and elegant parts." - Programming Pearls by Jon Bently
- "What makes Wallach a good Data General engineer is that he came up with a really elegant subset of those ideas—simple, sweet, cheap, efficient, clean." - Soul of a New Machine by Tracy Kidder
- "an architect who has to build on a difficult site, or a small budget, will find that he's forced to produce an elegant design." - Hackers & Painters by Paul Graham
- "The trick is first to strive for that elegance, and then, if we can't achieve it with an appropriate expenditure of resources, to make sure that, if we are forced to a complex solution, it's because the problem is complex, not just our solution." - Software Creativity 2.0 by Robert Glass
The consensus is that elegance is highly desirable, but what is it exactly? What makes one solution elegant and another awkward?
Authors elude its meaning but rarely explicitly define it. They regard it as Justice Potter Steward regards obscenity: "I know it when I see it." In this blog post, we'll explore the concept of elegance in software and propose two quantifiable attributes: symmetry and simplicity.
To understand the origin of elegance in software, one must recall the industry's early days when math and software were intrinsically linked. The first computer programmer, Ada Lovelace, was a mathematician[1]. Nearly all the pioneering applications of computing machines were scientific or numerical; therefore, programmers had a high degree of mathematical competency.
Math's influence on software is painfully evident by examining early programming languages. COBOL, Fortran, and LISP all have a math-focused design. The syntax of these languages was designed by and for mathematicians. Finding someone with a programmer or software engineer[2] job title was rare. The people writing the code were erudite professionals from other fields.
Early mathematicians transposed the concept of elegance from their domain and applied it to describe the quality of software solutions. Luckily, mathematical elegance is a more tangible concept. There are two attributes of elegant math: symmetry and simplicity. The following section examines each in turn.
Life on Earth evolved with bilateral symmetry, which may account for humans' almost inexplicable obsession with it[3]. Research indicates that perceived beauty highly correlates with symmetry[4]. Symmetrical preoccupation isn't new. Although not understood then, Plato's conception of beauty as applied to "Platonic Solids" correlates with our modern conception of symmetry.
At its very essence, math relies upon the concept of symmetry. Math is an abstraction that allows us to reason about categories of objects assumed to be symmetrical. All mathematical operations require an imposed artificial symmetry.
Consider this scenario: expressing the cardinality[5] of the people in a room necessitates the assumption that each person is symmetrical. Regardless of their unique attributes, each equates to the number one. Unlike people, summing numbers is possible. Imposing this artificial symmetry makes it possible to reason using abstract concepts. This type of math is elegant because it has symmetry with the real world[8]. Stated differently, mathematical symmetry implies congruence with the physical world. It enables us to count anything. Not all abstractions share this attribute.
Irrational numbers, such as pi, demonstrate a different type of abstraction. It isn't possible to define pi with infinite precision. Although immeasurably valuable, irrational numbers are only an approximation of the real world and, therefore, difficult to categorize as elegant.
In the ancient Pythagorean community, symmetry held immense significance. A profound dilemma arose when Hippasus stumbled upon the square root of 2. The revelation disrupted their belief in the absolute harmony of whole numbers, leading to such intense dissonance that, according to legends, they resorted to drastic measures, even drowning Hippasus to squelch the unsettling truth.
The key takeaway is that elegant math has perfect symmetry with the physical world. Approximating or bending reality isn't necessary with an elegant abstraction. Unfortunately, elegance is more than symmetry. Simplicity is also requisite.
Antoine de Saint-Exupéry said it best: "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."[6] Simplicity is boiling down a problem to its essential core. Representing an elegant solution in a more straightforward, easy-to-understand way is impossible.
It's important to note that, in this context, simplicity does not imply naivety or lack of intelligence. Einstein's theory of relativity (E=mc2) embodies elegance as it presents the most simple and concise representation of the abstract concepts it encompasses. It distills the profound complexity of space, time, and gravity into a comprehensible framework without sacrificing accuracy or depth. The remarkable elegance of Einstein's theory lies precisely in its ability to capture the intricate nature of the universe while retaining a clear and concise formulation.
The key takeaway is that simplicity is the ability to strip everything unnecessary, revealing the core of a problem or solution. True elegance is when complexity is distilled into a clear and concise form, fostering deeper understanding without sacrificing accuracy.
Having gained a solid grasp of symmetry and simplicity as applied to mathematics, defining elegant software solutions is a natural progression.
An elegant software solution has symmetry with the real world, meaning that understanding the domain is sufficient to comprehend the code. Software isn't elegant if a programmer must first study various tools and obtain tribal knowledge to contribute. Likewise, anything requiring users to deviate from natural domain activities to achieve an end lacks real-world symmetry.
Achieving simplicity requires solving the problem as straightforwardly as possible by avoiding superfluous design constructs and tools. It's about achieving the relevant outcome and nothing else. It's not possible to remove any constructs without sacrificing correctness. Simple software is impossible to express more intelligibly.
Please notice the absence of words like "concise" and "succinct" in the description above. Unlike math, writing software necessitates the use of computer languages. It's often possible to write code that is concise but cognitively complex[7]. Simple software is easy to understand, usually equating to succinctness but not always.
Armed with the criterion of symmetry and simplicity, identifying elegant software is tractable. Elegant solutions are maintainable and provide tangible value with minimal resources. Like mathematics, elegance isn't always achievable; however, it should be what every software professional strives for. The question becomes, how do I learn to write elegant code?
To truly appreciate elegance in software development, it is essential to cultivate an intuition for it. One practical approach is to examine existing elegant code closely. Luckily, two freely available sources are classic computer science algorithms and open-source code.
Some might question the relevance of studying algorithms, as modern tools often shield developers from directly implementing them. When was the last time you found yourself writing a sorting algorithm from scratch? However, the value of studying algorithms lies not in mindlessly regurgitating code but rather in the opportunity to scrutinize software's "greatest hits" of elegance meticulously. By immersing yourself in examples of elegant code, you greatly enhance your ability to write code that embodies the same level of elegance. This deliberate study provides valuable insights and techniques that can be applied to your software development journey, increasing the likelihood of producing elegant solutions. Many free algorithms courses exist, including one your humble author offers.[9] Thomas Cormen et al.'s book Introduction to Algorithms is another priceless resource.
Open-source projects offer a rich and diverse collection of codebases created by skilled developers across various domains. By delving into these projects, you can access real-world examples of code written by experienced practitioners. The Redis codebase[10] is a great place to start.
For a more concise example, please refer to How to Write a Spell Corrector by Peter Norvig[11]. The article is a bit dated, but Peter is a master of elegance. His code is timeless.
Elegant math is the simplest possible form of perfect symmetry with the world. The same applies to software: elegant code boils away superfluous constructs and has symmetry with its real-world purpose. The best way to learn how to write elegant software is by studying examples.
[1]In 1843, Ada started writing code for Charles Babbage's theoretical Analytical Engine. Her first algorithm calculated Bernoulli numbers. Although it never ran on an actual machine, this is widely considered the first computer program.
[2]The term "software engineer" was coined by Margaret Hamilton, a computer scientist who worked on the Apollo space program at NASA in the 1960s. It didn't come into vogue until the 1970s.
[3]The neurotic feeling of trepidation one feels when encountering hordes of multi-colored Post-it notes strewn about in a desultory manner stems from the perception of a lack of symmetry.
[5]Cardinality is fancy math lingo representing the number of elements in a set, helping us understand the size or count of the set's members.
[6]Wind, Sand, and Stars
[7]This Perl one-liner is an excellent example:
The code takes the keys from a hash, combines them into a single string, splits the string into pairs, and assigns them as key-value pairs in a new hash.
[8]In mathematics, perfect symmetry implies continuous rather than discrete measurement. This is a bit of minutia that we'll ignore. For the purpose at hand, assume perfect symmetry implies congruence with reality.
[9]https://hideoushumpbackfreak.com/algorithms/
[10]https://github.com/redis/redis
[11]https://norvig.com/spell-correct.html