What is the best way to model advanced parameters in Java?

I have a Java method that accepts 3 parameters, and I would like it to also have a 4th “optional” parameter. I know that Java does not support optional parameters directly, so I am encoded in the 4th parameter, and when I do not want to pass it, I pass null. (And then the method checks nullbefore using it.) I know this is pretty awkward ... but another way is to overload the method, which will lead to quite a lot of duplication.

What is the best way to implement optional method parameters in Java: using a parameter with a null value or overload? And why?

+3
source share
2 answers

Write a separate three-parameter method that will go into the 4-parameter version. Do not put it.

With so many options, you might want to consider a builder or the like.

+10
source

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
    }

}
+4
source

Source: https://habr.com/ru/post/1737352/


All Articles