Advantages of immutable objects:
1. An immutable object remains in exactly one state, the state in which it was created. Therefore, immutable object is thread-safe so there is no synchronization issue. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety.
2. Immutable classes are easier to design, implement, and use than mutable classes.
3. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
4. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).
5. Immutability makes it easier to parallelize program as there are no conflicts among objects.
6. The internal state of program will be consistent even if you have exceptions.
7. References to immutable objects can be cached as they are not going to change. (i.e. in Hashing it provide fast operations).
Disadvantages of immutable objects:
Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections. The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
Creating these objects can be costly, especially if they are large.
No comments:
Post a Comment