I read the chapter you stated, and I can see how you might be confused, as the chapter doesn't describe how you might use immutable objects.
Immutability is a core part of functional programming. To see how it works, consider this code:
MyImmutableClass newInstance = transform(MyImmutableClass originalInstance);
The transform
method accepts the originalInstance
object, transforms it (that transformation can be any operation), and returns a new object containing the transformation.
Why would you want to create a new object, instead of modifying an existing one?
- It creates a history of changes.
- It makes concurrency easier. Immutable objects are not subject to concurrency problems like race conditions. Functions using immutable objects can be easily decomposed into separate concurrent processes without problems.
- Immutable objects are easier to reason about.
In business applications involving CRUD operations, because you're typically already using a database with ACID guarantees, it's more common to simply mutate the values in the object you want to change, and then perform a Save (Update).