What Is Preferable Mutable or Immutable Classes?

What Is Preferable Mutable or Immutable Classes?

Immutable classes do promote object proliferation, but if you want safety, mutable objects will promote more object proliferation because you have to return copies rather than the original to prevent the user from changing the object you return.

Why is mutability bad?

Mutable objects reduce changeability. Mutable objects make the contracts between clients and implementers more complicated, and reduce the freedom of the client and implementer to change. In other words, using objects that are allowed to change makes the code harder to change.

What is the advantage of immutable class in Java?

Immutable classes are easier to design, implement, and use than mutable classes. Immutable objects are good Map keys and Set elements, since these typically do not change once created. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.