Search code examples
javaimmutabilityeffective-java

Need I make all classes immutable?


I read Effective Java, and there written

If a class cannot be made immutable, limit its mutability as much as possible...

and

...make every field final unless there is a compelling reason to make it nonfinal.

So need I always make all my POJO(for example simple Bookclass with ID, Title and Author fields) classes immutable? And when I want to change state of my object(for example user change it in table where represented many Books), instead of setters use method like this:

public Book changeAuthor(String author) {
   return new Book(this.id, this.title, author);  //Book constructor is private
}

But I think is really not a good idea..

Please, explain me when to make a class immutable.


Solution

  • No, you don't need always to make your POJO immutable. Like you said, sometimes it can be a bad idea. If you object has attributes that will change over the time, a setter is the most comfortable way to do it.

    But you should consider to make your object immutable. It will help you to find errors, to program more clearly and to deal with concurrency.

    But I think you quoting say everything:

    If a class cannot be made immutable, limit its mutability as much as possible...

    and

    ...make every field final unless there is a compelling reason to make it nonfinal.

    That's what you should do. Unless it's not possible, because you have a setter. But then be aware of concurrency.