Chapter 4. Immutability
Dealing with data structures—constructs dedicated to storing and organizing data values—is a core task of almost any program. In OOP, this usually means dealing with a mutable program state, often encapsulated in objects. For a functional approach, however, immutability is the preferred way to handle data and is a prerequisite for many of its concepts.
In functional programming languages like Haskell or even multiparadigm but more functionally inclined ones like Scala, immutability is treated as a prevalent feature. In those languages, immutability is a necessity and often strictly enforced, not just an afterthought to their design. Like most other principles introduced in this book, immutability isn’t restricted to functional programming and provides many benefits, regardless of your chosen paradigm.
In this chapter, you will learn about immutable types already available in the JDK and how to make your data structures immutable to avoid side effects, either with the tools provided by the JDK or with the help of third-party libraries.
Note
The term “data structure” used in this chapter represents any construct that stores and organizes data, like Collections or custom types.
Mutability and Data Structures in OOP
As an object-oriented inclined language, typical Java code encapsulates an object’s state in a mutable form. Its state is usually mutable by using “setter” methods. This approach makes the program state ephemeral, meaning any change to an existing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access