Which is the better way to simulate optional parameters in Java?
-
20-09-2019 - |
Question
I have a Java method that takes 3 parameters, and I'd like it to also have a 4th "optional" parameter. I know that Java doesn't support optional parameters directly, so I coded in a 4th parameter and when I don't want to pass it I pass null
. (And then the method checks for null
before using it.) I know this is kind of clunky... but the other way is to overload the method which will result in quite a bit of duplication.
Which is the better way to implement optional method parameters in Java: using a nullable parameter, or overloading? And why?
Solution
Write a separate 3-parameter method that forwards to the 4-parameter version. Don't kludge it.
With so many parameters, you might want to consider a builder or similar.
OTHER TIPS
Use something like this:
public class ParametersDemo {
public ParametersDemo(Object mandatoryParam1, Object mandatoryParam2, Object mandatoryParam3) {
this(mandatoryParam1,mandatoryParam2,mandatoryParam3,null);
}
public ParametersDemo(Object mandatoryParam1, Object mandatoryParam2, Object mandatoryParam3, Object optionalParameter) {
//create your object here, using four parameters
}
}