Overloaded method chaining

I have a function with an optional argument implemented as a pair of overloaded methods. This function calls another function that has the same optional parameter. The problem is that the lower-level function should use the default argument and the higher-level one shouldn't:

public void doTask(String arg1, String arg2) {
    // do a bunch of things
    smallstep(arg1, arg2);
    // do another bunch of things
}

public void doTask(String arg1) {
    doTask(arg1, null);
}

public void smallstep(String arg1, String arg2) {
    // do stuff
}

public void smallstep(String arg1) {
    smallstep(arg1, 1);
}

      

Basically the problem is that the function has doTask

to pass 1

as an argument (or call smallstep

with only one argument) if no second argument is specified, but passing null calls are both arguments.

In my particular case, the types are more complex and the methods are in different classes, so the default argument is smallstep

not visible to the containing class doTask

and shouldn't be anyway. Is there a way to handle this other than checking arg2 == null

and calling the appropriate function?

public void doTask(String arg1, String arg2) {
    // do a bunch of things
    if (arg2 == null) {
        smallstep(arg1);
    } else {
        smallstep(arg1, arg2);
    }
    // do another bunch of things
}

      

It clogs up quickly and doesn't seem very nifty to me ...

+3


source to share


1 answer


Use varargs on the optional parameter, allowing you to completely remove the overloaded implementation while retaining the intent of the original call when the inner method is called:

public void doTask(String arg1, String... arg2) {
    // do a bunch of things
    smallstep(arg1, arg2);
    // do another bunch of things
}

public void smallstep(String arg1, String... arg2) {
    String arg = arg2.length == 0 ? "some default" : arg2[0];
    // do stuff
}

      

While this allows the parameter to be used for more than one second, any additional functions can be ignored (as in this code), or you can be thrown IllegalArgumentException

if the length is> 1.



The existing calling code will be compatible with both your published code and that code (no external changes required).

Note that if varargs is called with no values, the method sees it as an empty array (not null).

+2


source







All Articles