Immutable Value Objects – What are their Advantages?
Immutable value objects can be validated on creation and never worry about validation again; if the state cannot be changed, then you know it’s always valid.
Value objects can be reused in different entities. For example: User and Location entities with Address value objects.
Value objects can be used as arguments for other methods in other classes.
Immutable value objects cannot have their state modified; if User and Location initially share the same Address value object, and the User at one point changes his address, a new Address object must be instantiated. If Address was mutable and User mutated Address, Location would have had an invalid Address. They prevent “strange behavior”.
Immutable value objects eliminate the need for defensive copies (you can be sure no one will change its value), and reduce the risk of program error.
Value objects make your design clearer.
Value objects encourage composition over inheritance.
Value objects can contain some specialized methods that only make sense in context of this value (and avoid duplicated code or weird Util classes).
Immutable value objects are always thread-safe. You don’t need a lock. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. The only synchronization needed is for destruction.
Immutable value objects make it easier to reason about the code, since you can make assumptions about variables and arguments that you can’t otherwise make.
Immutability is a fundamental principle in many functional programming languages – when you call a function with the same argument twice, you always get the same result.