So imagine we have a situation like this:
public class Bar1 {
public final int VALUE1;
public final double VALUE2;
public final String NAME;
/*DOZENS OF FINALS!*/
public Bar1(int v1, double v2, String name)
{
this.VALUE1 = v1;
this.VALUE2 = v2;
this.NAME = name;
}
}
and
public class Foo1
{
private Bar1 bar1;
private Bar1 bar2;
private Bar1 bar3;
/*Dozens of bars!*/
public Foo1( //We need to pass the values in here)
{
bar1 = new Bar1( //we need to initialise each of the bars. )
bar2 =...
bar3 = ...
}
}
What’s a good way of doing this? I think passing each one in as it’s own argument,
eg:
public class Foo1
{
private Bar1 bar1;
private Bar1 bar2;
private Bar1 bar3;
/*Dozens of bars!*/
public Foo1(int bar1Value1, double bar1Value2, String bar1String,
int bar2Value1, double bar2Value2, String bar2String,
int bar3Value1, double bar3Value2, String bar3String)
{
bar1 = new Bar1(bar1Value1, bar1Value2, bar1String);
bar2 = new Bar1(bar2Value1, bar2Value2, bar2String);
bar3 = new Bar1(bar3Value1, bar3Value2, bar3String);
}
}
is a huge pain in the ass.
I’ll post the solution I’ve come up with, but I’m wondering what other solutions there are.
Separate out your types. If you have dozens of fields, it’s almost certain that either:
Some of those fields are related to each other, so should be captured in their own type, e.g. if you have fields
address1,address2,address3,city,statethen that should be anAddresstypeSome of the fields aren’t related at all, and shouldn’t be in the same type to start with
I have never seen a well-designed class with dozens of fields.
Once you’ve cut down the number of fields, you won’t have a problem with an unwieldy constructor.
If you do still have a lot of fields, the builder pattern (as mentioned in comments) is indeed good, if a little tedious: have a mutable builder type (often a nested type), and then a
build()method which passes the builder itself to the constructor of the immutable type, which copies the values from the builder into the final fields.