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 Book
class 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With