6 Embracing purity with functional programming
This chapter covers
- Embracing functional purity
- Lambda expressions
- Simplifying collection processing with pipelines
We’re now halfway through our journey into the art of code. If everything went according to plan, you now have a keen eye for what makes code truly beautiful. Such code is pleasant to read because it tells a clear story, allows data to shine, and conveys its intentions with simplicity, clarity, and expressiveness.
Now that you are comfortable writing beautiful code in an object-oriented style, enriched by data-oriented principles, it’s time to explore new territory with the dimension of purity. Purity means that behavior remains isolated, predictable, and untouched by side effects or hidden state. It does not belong exclusively to functional programming, but functional programming offers one of the clearest ways to reach it in practice.
One strength of functional style is that it makes pure transformations easy to express: behavior becomes a sequence of operations through which data flows. For example, the following Java pipeline expresses a simple transformation:
List<String> titles = books.stream() .map(Book::title) .sorted() .toList();
It reads almost like a sentence: extract the titles, sort them, then collect the result. Control-flow noise disappears, leaving only the transformation visible.