When I have a function that might, or might not receive a certain parameter, is it better to overload the function, or to add optional args?
If each one has it's ups and downs - when would I use each?
When I have a function that might, or might not receive a certain parameter, is it better to overload the function, or to add optional args?
If each one has it's ups and downs - when would I use each?
If the language supports them properly (e.g. type-safety, if applicable), I would prefer optional arguments for the following reasons:
a
, b
and c
has these possibilities: nothing, a, b, c, ab, ac, bc, abc. It's 2^n
for different types, not n!
Assuming a constructor kind of situation: I often choose a fluent builder pattern to prevent situations with many options.
Eg.Ordering.natural().onResultOf(function).reverse().compound(Ordering.natural().onResultOf(function2))
is an example of calling a fluent builder interface implemented in Guava.
Of course you now need a separate object to hold the state of your builder, but you reduce overall complexity by separating behavior of constructing from behavior of the constructed.