So I've been reading Effective Java by Joshua Bloch and noticed two points which I actually have encountered in my work.
Point 1: Making setter methods to make code more readable. In his example, we have a class with a ridiculously huge constructor. When people instantiate the class, it's hard to tell what's going on with all the parameters. Thus, he suggested making a minimalistic constructor and have setter methods for all other options, so instead of...
MyClass clazz = new MyClass(a, b, c, d, e, f, g);
you would write....
MyClass clazz = new MyClass(a, b, c);
clazz.setDitto(d);
clazz.setEcho(e);
clazz.setFunzies(f);
clazz.setGumballs(g);
Which, as a huge supporter of readable code, I liked a lot.
Point 2: In general, he suggested having immutable classes. He goes into great depth on why having immutable classes is much better than having a class that could be in several different states. I can definitely say that he sold the idea to me, and I can't wait to make most classes I write from now on immutable, except....
What happens when you have an immutable class with a huge constructor? You can't make setter methods for it; that would break immutability. I tried skimming through the rest of the book, but I don't think he covers a solution for this.
There is the possibility of making one-time use setter methods, but just the fact that a setter method is available to a class that is supposedly immutability is disheartening, even if it does just throw an Exception if you try it subsequent times.
Does anyone have any good ideas on how to handle this problem? I'm currently facing this issue at work where I have an Immutable class with a huge constructor which I'd like to refactor to something that's more readable without breaking immutability.
One option is to provide a separate builder class that provides the setters, which is responsible for constructing the actual object.
In the second edition of Bloch's "Effective Java", item 2 illustrates this for an immutable class. The key ideas are:
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