Do I need to make all classes immutable?

I read Effective Java and it says

If a class cannot be made immutable, limit its variability in the same way as possible ...

and

... make the whole field final unless there is good reason to make it nonfinal.

So is it necessary to always make all my POJOs (for example, simple Book classes with ID , Title and Author fields) immutable)? And when I want to change the state of my object (for example, the user changes it in a table where many books are presented), instead of setters, they use this method:

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

But I'm really not a good idea.

Please explain to me when to make a class immutable.

+4
source share
3 answers

No, you do not need to always make your POJO unchanged. As you said, sometimes this can be a bad idea. If you mind, attributes that will change over time are the most convenient way to customize.

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

But I think you quote everything:

If a class cannot be made immutable, limit its variability in the same way as possible ...

and

... make each field final, if there is no good reason this is not a final.

What you gotta do. If this is not possible, because you have a setter. But then know concurrency.

+6
source

1. A POJO is a method with private Instance Variables with Getter and Setter .

2 .. Classes of type String class that require the behavior/implementation constant in should be final all the time , and not the one that needs to change over time.

3. In order to make a class immutable, the final one is not only a solution , you can have private Instance Variables , only Getter methods . And their status is set to Constructor .

4. Now, depending on your decision on coding, try to fix which fields should be constant throughout the program , if you think certain fields should be immutable , make them final.

5. The JVM uses the Constant folding mechanism to pre-calculate constant values.

+1
source

In the OOP world, there is a state . Specify all properties of the object. The return of a new object when the state of your object changes ensures that your application will work correctly in a parallel environment without any special things (synchronization, locks, atoms, etc.). But you always create a new object.

Imagine that your object contains 100 properties, or be a real set of 100 elements. To follow the idea of ​​immutability, you also need to copy this collection. This is a large memory, perhaps it is processed by the GC. In most cases, it is better to manually process the state of the object than to make the object unchanged. In some difficult cases, it is better to return a copy if the simultaneous problems are very serious. It depends on the task. There is no silver bullet.

+1
source

All Articles