Reputation: 20581
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.
Upvotes: 4
Views: 772
Reputation: 33534
1. A POJO
is one which has private Instance Variables
with Getter
and Setter
methods.
2. And Classes like String class
, which needs a constant behavior/implementation
at all time needs to be
final, not the one which needs to change with time.
3. For making a class immutable, final is not only the solution, One can have private Instance variables
, with only Getter methods
. And their state being set into the Constructor
.
4. Now depending on your coding decision, try to rectify which fields needs to be constant throughout the program, if you feel that certain fields are to be immutable
, make them final.
5. JVM uses a mechanism called Constant folding for pre-calculating the constant values.
Upvotes: 1
Reputation: 10789
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.
Upvotes: 1
Reputation: 31605
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.
Upvotes: 6