Java – invariance and readability
So I have been reading effective java written by Joshua Bloch and noticed two points I encountered in my work
Point 1: make setter methods to make the code more readable In his example, we have a class with a very large constructor When people instantiate this class, it's hard to say what's happening with all the parameters Therefore, he suggested making a simple constructor and setting the setter method for all other options, so it's not
You can write
As a huge supporter of readable code, I like it very much
Point 2: in general, he recommends using immutable classes He delved into why immutable analogies are much better than having classes that may be in several different states I can say for sure that he sold me this idea. I can't wait to make most of the courses I've written since now unchanged, except
What happens when you have an immutable class with a huge constructor? You can't make setter methods for it; This will destroy invariance I tried to skim through the rest of the book, but I don't think he offered a solution
It's possible to use a one-time setter method, but the fact that only a setter method can be used for a class that is considered immutable is frustrating, even if it just throws an exception on your subsequent attempts
Does anyone have any good ideas on how to deal with this problem? I'm currently dealing with this problem. I have an immutable class with a huge constructor. I want to refactor something easier to read without breaking invariance
Solution
One option is to provide a separate builder class that provides a setter that is responsible for constructing the actual object
In Bloch's second edition "effective Java", item 2 is immutable class, which illustrates this point The key ideas are:
>The builder has a variable field for each option. > The builder passes itself as a single parameter to the constructor of an immutable class