Assuming you have functions which take an increasing number of optional parameters (and a pseudo language which does not allow optional parameters and an arbitrary number of parameters) like this:
function doStuff(Param a)
function doStuff(Param a, Param b)
function doStuff(Param a, Param b, Param c)
What is a good way to unify them to a single call? I can imagine two designs:
Fall through everything:
function doStuff(Param a)
doStuff(a, defaultB)
function doStuff(Param a, Param b)
doStuff(a, b, defaultC)
function doStuff(Param a, Param b, Param c)
// magic goes here
- The Upside: Not much code duplication, easy changing of a single default parameter.
- The Downside: Many function calls, might render Stacktraces harder to read or useless.
Or directly call the 'last' function:
function doStuff(Param a)
doStuff(a, defaultB, defaultC)
function doStuff(Param a, Param b)
doStuff(a, b, defaultC)
function doStuff(Param a, Param b, Param c)
// magic goes here
- The Upside: Not many function calls, not worries if a new function is added into the chain.
- The Downside: Much code duplication, especially the default values.
What did I not think of?
a
andb
or neither), but the first still wins for minimizing bug duplication. BTW, typo: Middle overload implementation should be identical between the examples.