9 Data Classes
32
Be careful with immutability when using Java classes
If you decide to work with immutability, be aware that Java classes weren’t designed with
this in mind, and there are still some situations where you will be able to modify the state.
In the previous example, you could still access the
Date
object and change its value. The
easy (and unsafe) option is to remember the rules of not modifying the state of any object,
but copying it when necessary.
Another option is to wrap these classes. You could create an
ImmutableDate
class which
wraps a
Date
and doesn’t allow to modify its state. It’s up to you to decide which solution
you take. In this book, I won’t be very strict with immutability (as it’s not its main goal),
so I won’t create wrappers for every potentially dangerous classes.
Do'stlaringiz bilan baham: