Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 466
WelcomeTo Avatar asked Feb 20 '23 17:02

WelcomeTo


2 Answers

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.

like image 194
Thomas Uhrig Avatar answered Feb 22 '23 07:02

Thomas Uhrig


In OOP world we have state. State it's all properties in your object. Return new object when you change state of your object guaranties that your application will work correctly in concurrent environment without specific things (synchronized, locks, atomics, etc.). But you always create new object.

Imagine that your object contains 100 properties, or to be real some collection with 100 elements. To follow the idea of immutability you need copy this collection as well. It's great memory overhead, perhaps it handled by GC. In most situation it's better to manually handle state of object than make object immutable. In some hard cases better to return copy if concurrent problems very hard. It depends on task. No silver bullet.

like image 37
mishadoff Avatar answered Feb 22 '23 08:02

mishadoff