Objects can always be divided into two types:
- mutable (changeable)
- unbutable (unchangeable)
What are mutable objects: these are objects that have a state and have methods for changing this state. Those. Plain Old Java Objects with getters and setters that are familiar to us.
Unmucable - these are objects that, after their creation (invocation of the constructor), cannot change.
Each of these types has its advantages and disadvantages.
Advantages of unbutability:
- Immutable objects are good keys in Map and Set, since they usually do not change after creation.
- Non-confusion simplifies writing, using and understanding the code (the class invariant is set once and then unchanged)
- Immutability simplifies the parallelization of your program, since there are no conflicts between objects.
- The internal state of your program will be consistent, even if you have exceptions.
- References to immutable objects can be cached, since they will not change.
- Immutable objects are thread-safe, so you will not have problems with synchronization.
But you have to pay for these advantages, so you have to spend time creating new objects, every time you want to change the state, you will also have to think about which object can be called un-stable, because your object is unfortunately mutable. Those. you need to keep in mind the rules for creating unmovable objects, namely
- Make all fields private
- Do not provide getters / setters and other mutators.
- Ensure that methods cannot be overridden by creating a final class (Strong Immutability) or making your methods final (Weak Immutability)
- If the field is not primitive or unsuitable (like Date), then make a complete cloning of this object.
In general, the answer to your question: mutability itself is not a problem! It is actively used in the development, when the subject area is represented by an anemic data model (only getters / setters and there are no methods of behavior in objects), and everyone lives with it perfectly. But if you want to call an object immutable, use it as a key in a map, use it in a multithreaded environment, then take care of the points mentioned above.
Dateyou can change the state (for example, using thesetTimemethod), which does change the state ofEmployee, because it will change the date of employment. - Regent