Why objects must be Immutable
Immutable objects have multiple advantages over mutable objects which makes them the perfect building block to create software. You may already have many questions about the subject like:
- Why should I use immutable over mutable objects?
- How can I design software where no single object can be modified?
You'll see in this article what an immutable object is, the advantages to use them every time you can and how they can speed up your software developments.
Definition
To make it simple, a class is immutable when instances of this class cannot be changed once constructed. Immutable objects follow five rules, like explained in Java Effective by Joshua Bloch:
Final fields
No internal field can be reassigned after construction. This is very important: once the object has been constructed, there is no way to modify it.
public final class Truck {
private final String brand;
private final String model;
...
}