1 The aesthetics of code
This chapter covers
- What beautiful code means and why it matters
- The eight dimensions of beauty in code
- Refactoring code to eliminate the billion-dollar mistake
This book is about art, and you are the artist. Your medium is code. Your tools are logic and syntax. Your purpose is to shape ideas into code that is both clear and beautiful. Let’s demonstrate with a quick example in Java:
String city = null;
if (user != null && user.getAddress() != null
&& user.getAddress().getCity() != null) {
city = user.getAddress().getCity();
} else {
city = "Unknown";
}
Although this code works, it’s verbose and repetitive. It violates the law of Demeter, chaining multiple calls to reach deep into nested objects. Its intent, retrieving the user’s city, is buried under low-level defensive null checks. It’s hard to read, difficult to maintain, and, let’s not mince words, ugly. Let’s try again, this time with the added purpose of making it elegant:
String city = Optional.ofNullable(user)
.map(User::address)
.map(Address::city)
.orElse("Unknown");
This time, there’s no duplication and no clutter. The purpose is clear, the code reads as a story: get the address, get the city, or use “Unknown” if it’s missing. The code is clear, simple, readable and beautiful.