DEV Community

BjornHollander
BjornHollander

Posted on

Setters on immutable objects?

Hello everyone! Recently I encountered a class which was defined to produce immutable objects. It concerned a class which encompassed a time period, with a start date and an optional end date. However to my surprise I discovered the class also had a few setter methods.
Now I have to acknowledge that the setter methods did return a new instance and left the old object in tact (as is should!), but still something inside me found it strange to define these methods as setters. If someone by accident misses the immutable character of the class this could quickly lead to strange behaviour in the application.

Basically my question is, how do you feel about setter methods on a class defined to produce immutable objects?

Top comments (2)

Collapse
 
nickholmesde profile image
Nick Holmes

Formally, a setter is know as a mutator method. It's paradoxical to claim an immutable object has mutator methods. Setters do not formally return a value either. In many languages, you are not even able to return a value from a setter.

As this is a well understood concept, I would say its a bad practice to claim to follow it, but not.

That said, it's perfectly fine (and very common) to have methods on immutable classes that return new instances. This is the case with the String type in .Net, for example, and this is the source of many a bug;

myStr.ToUpper();

instead it should be

myUpperStr = myStr.ToUpper().
Collapse
 
bjornhollander profile image
BjornHollander

Agreed, I'm not apposed for methods to return new objects, it is simple the naming that got me thinking. :)