Hi all,
I would like to know your opinion on this topic.
Is making every domain entity immutable bring significant benefits or is it an example of over-engineering in most cases?
I am talking about entities that contain mutable state by design (not Value Objects or entities that are immutable by definition).
For instance:
class Person {
private final String ssn;
private final String position;
// constructor omitted
// mutable approach
public void promote(String newPosition) {
this.position = newPosition;
}
// vs immutable approach
public Person promote(String newPosition) {
return new Person(ssn, newPosition);
}
}
In general making everything immutable let you worry less about the concurrency issues (and as a java developer I always tried to follow this way).
But at the same time, the client code looks less attractive at times and I think that concurrency is not an issue in this case:
// somewhere in the application service
Person person = personRepository.find(ssn);
// the following lines are simplified but I hope you have get the idea of using "=" to be able to track changes
// because it is not always possible to make a chained "oneliner" like person.doOne().doTwo().doThree()
person = person.promote(position);
person = personRepository.save(person);
// do not return entity but convert it to some kind of DTO
return convert(person);
P.S. My post is about actions only. Because, IMHO, if the entity has a getter (no CQRS) that it should return only immutable representation of property (copy collections etc).
Thank you in advance for responses.