Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Considering object encapsulation, should getters return an immutable property?

Tags:

java

oop

When a getter returns a property, such as returning a List of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?

For example if a Contact object, has a getDetails getter, which returns a List of ContactDetails objects, then any code calling that getter:

  1. can remove ContactDetail objects from that list without the Contact object knowing of it.
  2. can change each ContactDetail object without the Contact object knowing of it.

So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?

like image 660
Behrang Avatar asked Sep 22 '08 10:09

Behrang


People also ask

When should an object be immutable?

2. What's an Immutable Object? An immutable object is an object whose internal state remains constant after it has been entirely created. This means that the public API of an immutable object guarantees us that it will behave in the same way during its whole lifetime.

Why should you make an object immutable?

Immutable objects are thread-safe so you will not have any synchronization issues. Immutable objects are good Map keys and Set elements, since these typically do not change once created. Immutability makes it easier to parallelize your program as there are no conflicts among objects.

Which objects should be called immutable?

The immutable objects are objects whose value can not be changed after initialization. We can not change anything once the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String class, etc. In a nutshell, immutable means unmodified or unchangeable.


1 Answers

It's a matter of whether you should be "defensive" in your code. If you're the (sole) user of your class and you trust yourself then by all means no need for immutability. However, if this code needs to work no matter what, or you don't trust your user, then make everything that is externalized immutable.

That said, most properties I create are mutable. An occasional user botches this up, but then again it's his/her fault, since it is clearly documented that mutation should not occur via mutable objects received via getters.

like image 181
Shachar Avatar answered Sep 28 '22 20:09

Shachar