Hi everyone. Some time ago I started reading Effective Java book and some of its items put more doubts on me than before I had. This is the case of Item 17 that says: "Classes should be immutable unless there’s a very good reason to make them mutable.". It's crazy for me because in my daily work I've never tend to use immutables over mutables and I've never seen before this practice in the codes I've worked with. For example, if I should deal with an entity User class that is populated by Hibernate annotations I don't make it immutable or in case or creating a service class, the same.
Rather my idea about immutables is that you can use them for such classes like a utility class or objects that don't use to change.
I'd like to know your point of view to know how much this book is right.
Writing immutable classes makes the application more resilient. I believe its more a way of thinking once you become more familiar with handling immutable objects. The benefits include thread safety for multi threaded application, easy to debug for issues etc.
I am learning to write java lambdas since last year and still not comfortable in writing stateless code yet. I do try to refactor my code to make it as compact as possible though. Hoping to improve with time.
Yes, the book is right, you should definitely strive to make most classes immutable.
The reason you don't often see this in real life is because people are lazy. They don't mind fixing bugs later if it means doing less work now.
When you write a class that only acts as a container of data for Hibernate to fill, you can and should also add another immutable class that you convert your data transfer objects to. Don't perform logic directly on your 'Hibernate classes'. Most people won't do this though, because they don't see the point and they are lazy, but it really helps preventing bugs.
Stephan van Hulst wrote:. . . The reason you don't often see this in real life is because people are lazy. . . .
Also, some people aren't taught about immutability when they start programming. If teachers and trainers don't update their knowledge and know 25‑year‑old practice, they will be unaware of changes and how immutability's importance has been recognised. Or people buy old textbooks and try to teach themselves from a book. Many books teach how to write mutable objects and say little about immutability. Even the Java™ Tutorials which has a nice section about immutability “hides” it in the concurrency section.