3

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?

froadie
  • 79,995
  • 75
  • 166
  • 235

2 Answers2

10

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
  • 145,806
  • 30
  • 211
  • 305
  • 1
    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 Mar 17 '10 at 15:15
  • 2
    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 Mar 17 '10 at 15:15
  • 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 Mar 17 '10 at 15:17
  • 1
    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. – BorisOkunskiy Mar 17 '10 at 15:40
4

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
  • 8,007
  • 44
  • 58