views:

200

answers:

2

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?

+10  A: 

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.

Tom Hawtin - tackline
aka, overloading
Robin Day
I guess that is the best way. If the parameters are of the same type, then you can use varargs - http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html
Sualeh Fatehi
What should the 3-parameter method forward as the 4th parameter...? Null? So then that only eliminates part of the problem - I still have to do the null-checking in the 4-parameter method. It just makes the interface simpler. Maybe it would be better to have the 4-parameter method call the 3-parameter method and do any necessary extra processing with the 4th parameter after the method call?
froadie
If there is an obvious default, then the default. If it's more complicated, then you'll probably want to separate out the bulk of the code into a private method.
Tom Hawtin - tackline
The term 'optional' implies, that there is either a default value or it is not used (in latter case, you are safe to use `null`). Anyway, your method's logic should be 'aware' of such thing, one way or another.
incarnate
+2  A: 

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
    }

}
JuanZe