Share E-Book

The Art of Code MEAP V02 The surprising power of beauty in software development (Sandrine Banas) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Software
Language English

Software development is an inherently creative activity that takes technical skill as well as artistry and craftsmanship. This unique book shows you how to improve the performance of your applications and your satisfaction as a developer by writing code that’s elegant, effortlessly comprehensible and a joy to maintain. The Art of Code isn’t a collection of subjective aesthetic opinions. It is a practical guide to recognizing and creating desirable code qualities, such as simplicity, purity, and expressiveness, that are demonstrably beneficial to you and your team, applicable to virtually any codebase, and beautiful. what's inside Create software that’s creative, purposeful, and impactful Build enduring systems with modularity, cohesion, and mindful coupling Improve AI-generated code Champion clarity, simplicity, and expressive design on your team Java 25 features like records, lambdas, and streams for elegant, maintainable code Coding sustainably about the reader This book is meant for all programmers even though examples use Java. What it teaches can be applied to any language. about the author Sandrine Banas is a senior Java expert, lead tech, and passionate software craftswoman with over 25 years of experience. An Oracle Certified Professional, she has spoken about these ideas at conferences including Devoxx, Volcamp, Mixit, Snowcamp, and Agile Grenoble.

Format PDF
Size 23.0 MB
1
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
MEAP Edition Manning Early Access Program The Art of Code The surprising power of beauty in software development Version 2 Copyright 2026 Manning Publications For more information on this and other Manning titles go to manning.com. © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 3
welcome Thank you for purchasing the MEAP for The Art of Code: The surprising power of beauty in software development. I hope you find it both useful and inspiring. After 25 years as a developer, I began to feel that something was missing beyond the principles of clean code. I wanted to give voice to the deeper purpose and the human dimension of our craft: the beauty and creativity we bring to software when we treat code as something more than just instructions for a machine. Especially in a time when AI seems to place our profession on uncertain ground, it feels more important than ever to explore what only we, as human developers, can create with care and intention. This book is written for developers who already feel confident in their skills and want to raise the quality of their work. If you’ve ever refactored a perfectly functional block of code simply to make it more elegant or more readable, because just working wasn’t good enough, then this book is for you. You’ll learn how to write code that is simple, expressive, and reads like a story, code that communicates its purpose effortlessly, in short, beautiful code. And beauty in code is more than an aesthetic ideal, it’s a practical foundation for writing software that lasts. By recognizing recurring patterns of beauty in code, you’ll sharpen your craftsmanship and build a toolkit for writing maintainable code that evolves gracefully over time. We’ll explore several dimensions of beautiful code, such as clarity of intent, purity, storytelling, durability, and sustainability (green coding). Each is illustrated with practical examples using modern Java features such as records, streams, and pattern matching. Your feedback during MEAP is essential. Please share your questions, thoughts, and suggestions in the liveBook discussion forum to help shape the final version of the book. Thank you again for joining early and for contributing to The Art of Code. I hope it helps you write software that not only works well, but endures and inspires. —Sandrine Banas © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 4
brief contents CHAPTERS 1 The aesthetics of code 2 Narrative code 3 The complex art of simplicity 4 Expressiveness with patterns and the enhanced switch 5 Clarity of intent through elegant data modeling 6 Embracing purity with functional programming 7 Handling failure with grace 8 Sustainability 9 Durable by design 10 Creativity in code and problem-solving Appendix A. © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 5
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: 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 = null; if (user != null && user.getAddress() != null && user.getAddress().getCity() != null) { city = user.getAddress().getCity(); } else { city = "Unknown"; } 1 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 6
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. Why make the extra effort to write beautiful code instead of stopping at merely usable code? Let’s not forget that before it’s executed by a machine, code is written to be read by humans. After all, machines need only ones and zeros, not the high-level languages we rely on today. The clearer and more elegantly structured the code is, the easier it becomes to read, maintain, and extend. This matters even more as code passes through many hands, with different skill levels, under tight deadlines and shifting business demands. Beauty in code is more than an aesthetic choice; it’s a practical necessity for building software that lasts. But it also speaks to something deeper: the developer’s need not just to produce code, but to find meaning in their craft by creating something they’re proud to leave behind. This book invites you to refine your technical skills by embracing a mindset that values beauty in every line of code. It explores the art and craft of writing elegant code with practical examples in Java. Each chapter will explore a dimension of beauty in code: storytelling, simplicity, expressiveness, clarity of intent, purity, durability, sustainability, and creativity. 1.1 Defining beautiful code Online searches for “beautiful code” often lead to formatting tools reflecting a broader tendency to equate code beauty with form over substance. When it is associated with substance, it often encounters resistance. Pursuing beauty in programming is seen as an unnecessary luxury in an industry pressured by time and driven by the need to produce working code quickly. However, the pursuit of beauty in code has profound practical benefits. It motivates teams to keep the code at a high quality standard and greatly simplifies onboarding for new developers by reducing the effort required to understand it. Before we discuss examples of elegant code, let's first define beauty in code with two foundational postulates. Having had many heated yet friendly discussions with colleagues about what constitutes good or readable code, I know there’s no absolute truth in programming. There are as many approaches to coding as there are developers. String city = Optional.ofNullable(user) .map(User::address) .map(Address::city) .orElse("Unknown"); 2 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 7
1.1.1 As developers, we can find common ground to define beauty in code The concept of beauty is shaped by shared experience—by community, language, and history. While we hold certain standards in common as members of a broader human culture, the differences are vast and meaningful. What we find beautiful changes from one culture to another, and from one era to the next. Despite these differences in how beauty is understood, can we, as developers from around the world, still agree on what beauty in code means? I believe we can because the developer world feels like a community of its own. Throughout my career, I’ve worked with people from many different nationalities and exchanged ideas with even more online. Despite differences in language, culture, or background, talking about code always felt like speaking a common language. When it comes to code, we share the same education, references, tools, and a common history of computing. We also belong to a vast online community where we continuously exchange ideas. So, around the subject of programming, as developers, we definitely form a community. Within that community, we share a common sense of what makes code beautiful, so even if we do not agree on each line of code in this book, I am certain we can agree on the broader principles. I won’t try to set these principles in stone. Coding looked very different fifty years ago, and it will certainly continue to evolve in the decades to come. What was once considered good practice, or beautiful, has changed and will keep changing. Because of this, defining beautiful code as some timeless, universal truth is impossible; its qualities reflect the evolving culture of the developer community. Yet, if there is one timeless truth, it’s not what makes code beautiful, but rather that code can be beautiful, given enough effort and craftsmanship from its creator. 1.1.2 The understanding of beauty can evolve with the level of knowledge Beauty is easier to appreciate when we understand the intention and craft behind it. I was reminded of this while visiting an exhibition of paintings by Joan Miró with my twelve-year- old daughter. She chose People at Night Guided by the Phosphorescent Trails of Snails (https://www. philamuseum. org/collection/ object/59573), painted in 1940, as her favorite painting. It depicts a dreamlike world of whimsical creatures. Much to her surprise, I said my favorite was Blue III (https://www. centrepompidou. fr/fr/ressources/ oeuvre/cpj56g), painted two decades later, part of a monumental triptych: a single red dot tethered to a line, a black mark, and an infinite field of deep blue. She looked at me, puzzled, and said, “But… that’s just two dots of paint. I could do the same thing at home.” Her reaction was honest and valid. Our ability to recognize beauty depends on our knowledge. Thanks to the exhibition and its explanations, I understood Miró’s journey toward radical abstraction and recognized the beauty of that pure, meditative painting. 3 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 8
The same is true in programming. A few years ago, one of my projects was upgraded from Java 7 to Java 8. Java 8 introduced some major changes in the language’s syntax with the addition of streams and lambdas. I took some time to get up to speed with these new features, and then enthusiastically started using them in the codebase. But a few weeks later, I realized I was the only one doing so. Everywhere else, traditional for-loops remained the norm. Curious, I asked around. Most of the feedback I received was that streams made the code harder to read and understand. I proposed a short session to walk the team through the changes introduced in Java 8. It only took two hours. During that time, I saw eyes light up, and for the first time, I started hearing more positive reactions: “Oh, that’s actually simple.” After that, more streams and lambdas began appearing in our codebase. Before they had the right understanding, my teammates found these new features confusing, even ugly. But once they grasped how they worked, their perspective changed. To fully appreciate the beauty of something, whether a painting or a piece of code, you need the right level of knowledge: how it works, where it comes from, and why it was created. Depending on your experience with Java, some examples in this book may feel complex, and you might not agree on their beauty. If that happens, take a step back and let the understanding settle. Try using it in your own code, make it yours, and only then, once you fully understand it, judge its beauty. BEAUTIFUL CODE AND AI In today’s development landscape, it's nearly impossible to write a book about programming without touching on the subject of AI. As a developer, I've integrated AI into various parts of my workflow, particularly for: Explaining a piece of code Creating Javadoc documentation Generating boilerplate code, especially unit tests Helping solve complex bugs Refactoring legacy code Writing classic implementations of simple algorithms That said, I don’t rely on AI to write core application logic. At the time of writing, the output is often interesting, but rarely production-ready. It typically resembles work from a keen junior developer: promising, but in need of detailed guidance on business rules and existing architecture, multiple clarifications, and extensive iteration before becoming truly usable. 4 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 9
When it comes to beautiful code, the results are even more inconsistent. A simple prompt like “make this code beautiful” usually falls short. I always need to add explicit instructions like use functional programming, prefer Optional over null, apply specific features or patterns, to steer the output in the right direction. In these cases, the extra effort often feels like a waste of time compared to simply writing the code myself. That said, for projects with simple business logic that do not require long-term support, the results can be quite sufficient. For enterprise-grade projects, with complex business rules, often spanning several repositories, and involving intricate interface dependencies with external systems, quality and consistency are crucial to ensure long-term maintainability. And AI, at least for now, has not proven capable of replacing a human developer. It has, however, proven to be a helpful tool to assist one. 1.1.3 The patterns of beautiful code So, what makes a piece of code appealing to us as developers? Defining beauty in code is a unique challenge, since it relies not on visual or sensory appeal, but on intellectual qualities. The origin of the word beauty isn’t tied to the senses either; it points to something well-crafted and harmonious. NOTE The word “beauty” comes from the Old French biauté, which in turn derives from Old Latin duonus, meaning “good.” From its earliest use, beauty was first tied to the idea of something being well-crafted, harmonious, and right. Another field closely related to coding and often described as beautiful by its practitioners can offer a path to defining beauty in code: mathematics. G. H. Hardy, known for discovering the brilliant, self-taught Indian mathematician Srinivasa Ramanujan, explained the idea of beauty in mathematics in his book A Mathematician’s Apology: “A mathematician, like a painter or a poet, is a maker of patterns. If his patterns are more permanent than theirs, it is because they are made with ideas. […] The mathematician’s patterns, like the painter’s or the poet’s, must be beautiful; the ideas, like the colors or the words, must fit together in a harmonious way.” Inspired by mathematicians, I began searching for patterns in code that could help explain beauty. Like in mathematics, beauty in code is revealed in the form of higher-order structures, making the code not just functional but deeply satisfying. Think of functional programming, which draws directly from mathematical logic to promote clarity. Or expressive power, which mirrors the mathematical pursuit of the most concise and elegant representation of a problem. 5 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 10
Recurring patterns tend to appear whenever code feels beautiful: storytelling, simplicity, expressiveness, clarity of intent, purity, and durability. Other dimensions of beauty go beyond algorithms and reflect something deeper: the intention behind the code. That’s why sustainability and the environmental cost of our work also deserves a place in the discussion. And finally, at the center of it all is creativity, the force that brings every other pattern into harmony. These eight dimensions will be explored in detail throughout this book. To present a high-level view of beautiful code, I needed a model that could represent these eight dimensions. Initially, I considered using a classic pyramid model. However, I quickly realized that organizing each quality in a layered hierarchy posed a problem. None of the dimensions seemed inherently more important than the others. Each one can stand on its own, yet they often overlap. Take purity, as found in functional programming, for instance. It can exist independently and contribute to elegant code. However, most dimensions are strengthened by the presence of others. Purity taken to an extreme can lead to complexity and reduced readability. To be truly elegant, it relies heavily on expressiveness and simplicity. Similarly, storytelling achieves maximum impact when it is rooted in simplicity, expressiveness, and clarity of intent. The model needed to reflect this dynamic, a space where these qualities coexist independently while still reinforcing one another, where creativity sits at the center, nourished by the others, and durability serves as the foundation. One model perfectly met all those criteria: the rosette, shown in figure 1.1. 6 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 11
Figure 1.1 Beautiful code: a rosette with 6 petals. The rosette captures the idea that beauty in code arises from the interplay of multiple dimensions, each reinforcing the others to create a whole that is greater than the sum of its parts. Let’s take a closer look at each of these dimensions, which will be described in more detail throughout the book. STORYTELLING Since readability is perhaps the most universally accepted trait of beautiful code, and already well covered in many great books, I won’t repeat those lessons here. Instead, I want to offer a fresh perspective by looking at readability through the lens of storytelling. In his book Clean Code, Robert C. Martin compares programming to storytelling: 7 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 12
“The art of programming is, and has always been, the art of language design. Master programmers think of systems as stories to be told rather than programs to be written. They use the facilities of their chosen programming language to construct a much richer and more expressive language that can be used to tell that story.” Readability is a core aspect of programming craftsmanship, but readable means more than just easy to read; it means enjoyable to read. And what’s more enjoyable than a good story? In chapter 2, we will define a new genre, narrative code, where the clarity of logic shines through the beauty of storytelling. SIMPLICITY Simplicity is one of the most powerful and least understood qualities of beautiful code. Software is in constant flux, growing more complex with every new feature. Simplicity is what keeps code understandable and maintainable. True simplicity isn’t the absence of complexity; it’s the art of refining complexity into its clearest, most elegant form. Making something inherently complex appear simple is the mark of a master. We’ll explore six practical levers to simplify code in chapter 3. EXPRESSIVENESS Mastering a language’s expressiveness is a key aspect of crafting beautiful code. It means embracing the full potential of the language to translate your ideas into clear, concise, and elegant solutions, without struggling, twisting syntax, or stretching logic just to make things work. Recent additions to Java, especially the enhanced switch and pattern matching, were designed to enhance its expressive power. Chapter 4 will explore how to use them to write code that is a pleasure to write and read. CLARITY OF INTENT Clarity of intent ensures that your code effortlessly communicates its purpose. One powerful way to achieve this is by structuring code around the data itself. Newer features in Java, such as records, make it easier to model solutions with data at the center, and chapter 5 will explore how to leverage them effectively. PURITY In functional programming, purity means functions that are predictable, side-effect-free, and consistent. It encapsulates a concept in its simplest, purest form: input goes in, output comes out, without surprises. By embracing these principles, functional programming brings mathematical beauty directly into the code. Purity increases testability, readability, and reusability, helping to reduce bugs, as we will explore in chapter 6. 8 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 13
DURABILITY Durability is about creating designs that can stand the test of time, even as they adapt to new demands. Although predicting future changes is impossible, and real-world constraints often lead to quick fixes and compromises, a good design from the start can provide the flexibility and structure needed to evolve gracefully over time rather than break quickly under pressure, as we will discuss in chapter 10. SUSTAINABILITY Sustainable (or green) coding is about designing software with minimal environmental impact. It means reducing electricity consumption and extending the lifespan of hardware to lower the carbon footprint of digital infrastructure. The goal is to build software that meets client needs while also respecting the planet. This book will focus on practical, server-side green coding patterns, emphasizing concrete techniques applicable in Java, which we will explore in depth in chapter 11. CREATIVITY In software, creativity rarely means inventing something entirely new. Instead, it thrives on innovative problem-solving to real-world challenges using the tools at your disposal: your knowledge, your passion, your concentration, and your tenacity. Sometimes, creativity means diving deep into the problem. Other times, it means stepping back to see it more clearly. It’s a process of exploration, research, iteration, and ultimately insight that leads to an elegant solution. In chapter 11, we will explore how to cultivate this kind of creativity in your daily coding practice. 1.2 Why use Java to demonstrate beauty in code? When I began writing this book, some asked why I chose Java to demonstrate beauty in code. Of course, beauty in programming can be found in any language. But I needed one language to carry the message and support a practical demonstration, and Java felt like the right choice. The first reason is Java’s wide adoption, which makes it a uniquely relevant choice. It powers everything from enterprise systems and trading platforms to Android apps and cloud microservices. With a mature ecosystem, a vast open-source community, and decades of accumulated knowledge, lessons about writing beautiful Java code apply across nearly every industry. 9 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 14
Another compelling reason is its clear commitment to backward compatibility. Code written in earlier versions can (mostly) still run today on modern JVMs. That stability is part of what made Java such a reliable choice for enterprises, especially when they are stuck on older Java versions, often due to dependencies, integration constraints, or the high cost of upgrading, and cannot refactor their entire project just to benefit from a Java upgrade. But it also means that, even thirty years later, Java developers are still free to write code as if it were the first version, overlooking powerful new features designed to make the language more expressive and maintainable. Some languages, such as Haskell, make it incredibly hard to write ugly code thanks to their strong static typing, concise syntax, and emphasis on pure functions and immutability. Java doesn’t, partly because of that heavy legacy baggage. It gives you complete freedom to write beautiful code, terrible code, and everything in between. And that’s exactly why it’s such a compelling language for exploring the nature of beauty in code. Sometimes, the only way to demonstrate beauty is by using ugliness as a stark contrast and a starting point. But I have another, more personal reason to choose Java. I’ve spent 90% of my career writing Java, and I’ve loved it. I never really developed a taste for the other languages I used, and I’ve always found my way back to Java. So, it’s not just the language I feel most confident using for this exploration, it’s the one I genuinely want to use. All code listings in this book use Java 25, the latest version available at the time of writing. Thanks to Java’s strong backward compatibility, this code will continue to run on future JVM versions, even those that haven’t been released yet. Still, not all examples necessarily require Java 25. Many of the features shown in this book were introduced in earlier versions. Depending on your company or the project you’re working on, you might be limited to a specific Java version. That’s why I’ll mention the minimum required Java version for each feature I demonstrate, so you’ll always know what works in your environment. You'll need a few essential tools to follow along with the code examples in this book. First, make sure you’re using Java 25 or a more recent JDK. We’ll use some of the latest features, such as switch expressions, pattern matching, sealed classes, and records, so a recent Java version is required to run all the code listings in this book. INSTALLING JAVA The Java Development Kit is available from multiple sources. Since 2007, it has been licensed under GPLv2 with classpath exception, allowing users to run, share, and modify the software freely. Here are the most common distributions: 10 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 15
Oracle, which acquired Sun Microsystems (the original creator of Java) in 2009, long provided the official JDK and still owns the Java brand (https://www. oracle.com/ java/). Oracle’s JDK is free for commercial use under the No-Fee Terms and Conditions (NFTC) since Java 17, but only until one year after the next long-term support (LTS) release. After that, a commercial subscription is required to continue receiving updates. OpenJDK (https://jdk. java.net/), a free and open-source implementation maintained by a broad community, remains popular. Vendors such as Amazon (with Corretto) and Eclipse (with Temurin) have also released their own compliant, production-ready JDKs. You can manually download a JDK from the vendor’s site, unzip it, and set your JAVA_HOME environment variable. You can also use a package manager like Chocolatey on Windows, Homebrew on macOS, apt on Ubuntu/Debian, dnf on Fedora/Red Hat, or pacman on Arch Linux for easier installation. You’ll also need an IDE (Integrated Development Environment). Not all IDEs support the latest Java features, especially if you’re using an older version. It’s worth checking your IDE’s website for compatibility or updating to the latest version. Among the most popular choices, IntelliJ IDEA is the most widely used, with others like Visual Studio Code, Eclipse, and NetBeans also offering solid support. Although Java is the constant throughout the book, most principles apply to other languages as well. The dimensions of beautiful code are not tied to Java’s syntax or libraries. They are universal qualities of well-crafted software. You could apply the same ideas in object-oriented languages like C#, C++, or Kotlin, in dynamically typed languages like Python or JavaScript, or in purely functional ones like Scala, Haskell, or Elm. While the examples in this book use Java to illustrate the concepts, the mindset and practices can help you write clearer, more elegant, and more maintainable code in any language. 1.3 A simple example of beautiful code Because beautiful code can feel abstract, the best way to explain it is to start with a concrete example, one that shows how ordinary Java code can shift from painful to elegant. We won’t dive into all the details yet. Those will come in later chapters, but this brief example will give you a first glimpse of how beautiful code feels in practice. 11 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 16
1.3.1 The null horror maze Let’s start with something every Java developer knows all too well: null handling. It often forces developers into heavy defensive programming, and the code becomes bloated with null checks, and always at risk of failure from a single forgotten condition. I’m presenting the following snippet without explanation intentionally. That’s how we often encounter code: dropped into it, expected to understand what it does and why it matters, despite the clutter: This type of code, along with its cumbersome if condition, can be found in nearly every Java class on the planet. After going through the noise, this code appears to do just one thing: retrieve a value. But why exactly does it feel so ugly? First, this code contains considerable duplication. For example, product.pricingDetails() is repeated multiple times. Furthermore, most of the code focuses on low-level technical details with null checks (null handling is one of the rare cases in Java where developers are forced to think explicitly about how values are stored in memory). Only one line directly represents the actual business intent, getting the price, and it’s buried among technical checks, greatly reducing readability. The code is also fragile. If one of the null checks is forgotten, the compiler won’t complain, making it easy to overlook during a refactor. And it violates a key design principle: the law of Demeter, also known as the principle of least knowledge. This principle states that a given object should only talk to its immediate collaborators, not to strangers buried several levels deep. In practical terms: don't chain multiple method calls to reach what you need. The expression product.pricingDetails().discountedPrice() reaches too far, exposing the structure of internal objects and tightly coupling the code to their implementation. It assumes knowledge of both Product and the internals of its PricingDetails, making the code brittle. Reading this kind of code can feel like being trapped in a horror movie, where a desperate victim frantically searches for the exit of a nightmarish maze, fearing that behind each door lurks the dreaded NullPointerException monster. As a Java developer, you've probably wandered that maze hundreds of times. You've told yourself, “There's no better way out.” But let me show you another path: BigDecimal price = null; if (product != null && product.pricingDetails() != null && product.pricingDetails().discountedPrice() != null) { price = product.pricingDetails().discountedPrice().amount(); } 12 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 17
This version eliminates duplication, removes the clutter of manual null checks, and expresses the business logic in a clean, readable chain of transformations. Each step is narrow in scope, with clear intent. Despite the chaining, it doesn’t violate the Law of Demeter. Each call accesses only one level of responsibility at a time, without manually navigating deep into the object graph. Most importantly, the purpose of the code is now obvious; it guides us smoothly and directly to the exit, no maze: extract the price if it's available. If this example feels a little abstract right now, that’s okay. We’re going to break it down step by step in the pages ahead. You’ll learn how each part works in detail. What matters here is recognizing that transformation is possible, that beautiful code is both a mindset and a skill you can practice. 1.3.2 A classic scenario Let’s retrace our steps through the maze and break down the problem one decision at a time. Consider the following practical scenario: retrieving the price of a product. If the product has a discount, we want the discounted price. If no discount is available, we fall back to the base price. At first, this seems like a simple task. However, as illustrated in figure 1.2, the product, its pricing details, the discounted price, and the base price can all be absent. Figure 1.2 A product may have a discounted price, a base price, both, or none. Optional<BigDecimal> price = Optional.ofNullable(product) .map(Product::pricingDetails) .map(PricingDetails::discountedPrice) .map(Price::amount); 13 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 18
The class model consists of a Product object that contains a PriceDetails field. PriceDetails includes both the discounted price and the base price, as shown in figure 1.3. Figure 1.3 UML Class diagram showing a Product with nested pricing details. TIP In Java, use BigDecimal to calculate financial amounts. Unlike float or double, BigDecimal gives exact control over decimal precision and rounding behavior, which is vital for accuracy-dependent financial computations. In an ideal world, to get the amount we could simply write: But in the harsh reality, if even one link in that chain is null (meaning it holds no value), the program would throw a NullPointerException, one of the most common (and dreaded) pitfalls in object-oriented programming. NullPointerException signals a coding error that cannot be detected at compile time, only appears at runtime, and only with the right dataset. They represent programming errors, not recoverable conditions. These exceptions should not be caught or propagated further; they should crash the program immediately at the point of failure, making the root cause visible and ensuring the issue is detected and fixed as early as possible. BigDecimal price = product.pricingDetails().discountedPrice().amount(); 14 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 19
The only way to prevent it is to check whether a reference is null before using it. In Java, checking for nullity can quickly become a verbose struggle. Writing reliable code requires tediously checking each nullable type, as shown in listing 1.1. In this listing, every && condition is a manual null check, and product.pricingDetails() is called multiple times. This clutters the logic. Missing even one of these checks could cause the code to fail at runtime. NOTE Other languages have tackled the same problem brilliantly. For instance, in Kotlin, the safe call operator (?.) allows elegant access to deeply nested properties without manual null checks, so we can directly write: val price = product?.pricingDetails?.discountedPrice?.amount If any part of the chain is null, the entire expression safely returns null. Other languages like Groovy, Swift, and TypeScript offer similar operators. Navigating this maze is painful, but that is not the only problem. The method also returns a null, the most problematic kind, handing the issue back to the caller when no price exists. Consequently, every place that calls getFinalPrice() is burdened with the same tedious null checks to guard against failure or risk a NullPointerException (or NPE for short) as shown below: Listing 1.1 Getting the final price of a product #A Navigating Java’s mandatory null-check maze. #B Still passing the pain. #C The only lines that truly deliver business value. public BigDecimal getFinalPrice(Product product) { if (product != null #A && product.pricingDetails() != null) { #A if (product.pricingDetails() #A .discountedPrice() != null) { #A return product.pricingDetails() #C .discountedPrice().amount(); #C } else if (product.pricingDetails() #A .basePrice() != null) { #A return product.pricingDetails() #C .basePrice().amount(); #C } } return null; #B } 15 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
Page 20
THE NULL ORIGIN STORY So, who created the null monster? The concept of null dates back to the 1960s. During this fertile period for computing and innovation, high-level languages were emerging, allowing developers to break free from assembly language. Each iteration, each new language, brought higher levels of abstraction, enriching syntax and ease of use. Sir Charles Antony Richard Hoare, then known as Tony Hoare, was a young, enthusiastic, but inexperienced developer who proposed a contribution to the ALGOL W language: using null to represent a pointer without value. At the time, the idea was controversial, but it was ultimately adopted and later reused in many languages, including C/C++ and then Java. In a 2009 conference, Sir Hoare publicly offered a humorous mea culpa, calling his idea a “billion-dollar mistake.” He was referring to the astronomical cost of bugs caused by null references and the time wasted adding clunky code to avoid them. He admitted that other solutions existed, but chose this one because it was the easiest to implement at the time, without foreseeing the impact it would have. To sum up, defensive guards against null clutter the code and obscure its intent. Reaching for values deep in an object graph is not just verbose, but also fragile, and makes bugs easy to introduce. However, null, though a low-level remnant of a bygone era, is deeply rooted in Java and won’t disappear anytime soon. But where there is ugliness, there is potential for beauty, and for that, there’s one simple rule, almost a game: eliminate the word “null” from your code as much as possible, without compromising robustness. 1.3.3 Enter Java 8 to the rescue Fortunately, modern languages provide safer alternatives. In Java 8, there’s a better approach with Optional. The Optional class was introduced as the modern way to help developers properly rid their code of null references. It functions as a container that may hold a valid object, or nothing at all (as shown in figure 1.4), reminiscent of Schrödinger’s box, with a cat that is simultaneously alive and dead until observed. BigDecimal price = getFinalPrice(product); if (price != null) { System.out.println(price); } else { System.out.println("No price"); } 16 © Manning Publications Co. To comment go to liveBook Licensed to Ibrahim Mohammed Mohammed <ibrahim@dotnetebusiness.com>
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List