I have a class with some private final fields:
public class ClassA {
private final Object field1;
private final Object field2;
...
}
The class has several different constructors, with a variety of arguments:
public ClassA(Object arg1, Object arg2);
public ClassA(int arg1, String arg2, boolean arg3);
These constructors calculate the values to put in the final fields.
Ideally, I would like to do something like this:
public ClassA(Object arg1, Object arg2) {
... // error check params
Object value1 = ... // calculate value 1 based on args
Object value2 = ... // calculate value 2 based on args
init(value1, value2);
}
public ClassA(int arg1, String arg2, boolean arg3) {
... // error check params
Object value1 = ... // calculate value 1 based on args
Object value2 = ... // calculate value 2 based on args
init(value1, value2);
}
private void init(Object arg1, Object arg2) {
... // error checks on combination of calculated arg1 and arg2 values
... // in reality there are more than 2 args, and this logic is fairly complex
field1 = arg1;
field2 = arg2;
... // other common initialization code, depends on field1 and field2
}
In order to reuse the assignments and common initialization code. However, since the fields are final, they can only be assigned in the constructor calls.
Can't get away from using public constructors to make objects the in this case, so any type of factory methods aren't possible. It would be nice to keep the combination error checks on the arg1, arg2 values in the same block as the assignments of them to the ClassA fields. Otherwise I would split init()
into 2 functions, one pre-assignment of final fields and one post assignment of final fields, and make my constructors look like:
public ClassA(int arg1, String arg2, boolean arg3) {
... // error check params
Object value1 = ... // calculate value 1 based on args
Object value2 = ... // calculate value 2 based on args
preinit(value1, value2); // error checks combination of values
field1 = value1;
field2 = value2;
postinit(); // other common initialization code
}
Suggestions? Is there any way to avoid this, or am I stuck splitting the init()
function?