Design Patterns – What is This Pattern Called?

design-patternsmethod-overloading

Is there a name for this pattern where an API offers several variations of a method (differing in number of parameters) and internally forwards them with default parameters like this:

public void doSomething(Object one) {
    doSomething(one, null);
}

public void doSomething(Object one, Object two) {
    doSomething(one, two, null);
}

public void doSomething(Object one, Object two, Object three) {
        // real implementation here
}

Best Answer

If the delegation (and the default parameters filled in) are part of the function's contract, for example, if the DocString says

doSomething(one, two) is equivalent to doSomething(one, two, null).

then I refer to these as convenience overloads or convenience methods as they simply save the user some typing but don't do anything the user couldn't have done otherwise.

If the fact that the function simply delegates is not made public, then it is just an arbitrary implementation detail and probably does not deserve a special name.

I've picked this term up from the official Java documentation where it is used quite often.

A related idiom is to have a bunch of overloads for some public method doSomething that do nothing more than determining some parameters to then delegate to a private method doSomethingImpl. This is something different as the user is not aware of the existence of the doSomethingImpl method (and couldn't possibly call it). I have heard the doSomethingImpl be referred to as “worker method” or “workhorse” but those are probably very colloquial terms.

Related Topic