Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining overloaded methods

Tags:

java

I have a function with an optional argument, implemented as a pair of overloaded methods. This function calls another function, which has the same optional parameter. The problem is that the lower-level function is supposed to use a default argument while the higher-level one is not:

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);
}

So basically the issue is that the doTask function should pass 1 as the argument (or call the smallstep with just one argument) if the second argument isn't provided, but passing null calls the one with both arguments.

In my specific case, the types are more complicated and the methods are in different classes, so the default argument of smallstep isn't visible to the class containing doTask and shouldn't be anyway. Is there a way to handle this besides checking for arg2 == null and calling the respective 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
}

This gets cloggy quickly and doesn't seem very elegant to me...

like image 249
scenia Avatar asked Apr 26 '26 13:04

scenia


1 Answers

Use a varargs for the optional parameter, allowing you to delete the overloaded implementation entirely while preserving the intention 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
}

Although this allows more than one second parameter, any extras can either be ignored (as in this code), or you could throw an IllegalArgumentException if length > 1.

Existing calling code would be compatible with both your posted code and this code (no external changes required).

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

like image 137
Bohemian Avatar answered Apr 28 '26 02:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!