r/javahelp • u/[deleted] • Oct 05 '20
Workaround How would I shorten my Constructors?
I have this user class that contains a long list of constructor params. I also need usage for both smaller Users with less info, I don't want to explicitly write all those constructors. Anything I can do?
6
u/NautiHooker Software Engineer Oct 05 '20
one way to do this is to add setter methods to the class and remove some parameters from the constructor.
Then you could do something like this:
User user = new User();
user.setName("Carl");
user.setAge(5);
...The problem with this approach is that you allow the creation of a User object without giving it any values. So essentially its an unfinished object. If you later on forget to call some important setter method this might create bugs in your program which could have been avoided by forcing the passing of values to a constructor.
-8
Oct 05 '20
yes, and those setters look really tacky
4
u/_jetrun Oct 05 '20
and those setters look really tacky
What do you mean?
1
Oct 06 '20
like it seems weird to follow an Object initialization with a whole list of setters.
1
u/_jetrun Oct 06 '20
Why?
As OP mentioned, the issue with delegating initialization to setters is that you don't have a guarantee that the object will be initialized in a consistent state. Personally, I'm not a fan of mutable objects in general, so I tend to think deeply about even including setters on objects I create, but outside of that, I don't see what exactly is 'weird' about using this regular language convention.
1
10
u/King5lay3r Oct 05 '20
Sounds like a problem the Builder Pattern was made for. Whenever constructor has too many params it becomes unreadable and difficult to maintain. So we follow Builder design pattern in such case. You can read about it here: Builder pattern
6
u/philipwhiuk Employed Java Developer Oct 05 '20
In addition to the builder pattern, normally lots of parameters implies a refactoring is possible. Two possibilities:
The class does too much
The parameters can be grouped as an object which provides useful functionality.
For example 1:
BoltAndWidgetCreator(boltSize, widgetSize, boltsAreThreaded, widgetsArePointy)
Might be refactored to:
ConstructionToolsCreator(BoltCreator boltCreator, WidgetCreator widgetCreator)
For example 2:
WidgetToolCreator(toolWidth, toolHeight, toolLength, toolIsPointy)
could be refactored to:
WidgetToolCreator(toolDimensions, toolIsPointy)
1
u/knoam Oct 06 '20
Embrace your IDE. Intellij has a wizard that will take care of some of the tedium.
1
23
u/djnattyp Oct 05 '20
Use the Builder pattern or the built in versions from Lombok or autovalue.