chapter one

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.

1.1 Defining beautiful code

1.1.1 As developers, we can find common ground to define beauty in code

1.1.2 The understanding of beauty can evolve with the level of knowledge

1.1.3 The patterns of beautiful code

1.2 Why use Java to demonstrate beauty in code?

1.3 A simple example of beautiful code

1.3.1 The null horror maze

1.3.2 A classic scenario

1.3.3 Enter Java 8 to the rescue

1.4 From craftsmanship to artistry

1.5 Summary