Search code examples
javaoverloadingoptional-parametersmaintainability

What's the best design when adding in optional parameters in languages that don't support it?


Say I have

void foo(int a);

and I want to add in an optional parameter using a language that doesn't support it (i.e. Java):

void foo(int a, int optionalParam);

Lets say I'll set the default to be 0.

Now in my code base I have lots of calls to foo(int a)

Is it better to

A) modify foo(int a) { foo(a, 0); } so I don't have to change everywhere that calls foo(int a) to something like foo(a, 0);

or

B) remove foo (int a) and replace everywhere that calls foo(int a) with something like foo(a, 0);

A is the most convenient, but I thought it may be more difficult to maintain if I put in a new overloaded method every time I wanted to add an optional parameter.


Solution

  • Strictly speaking, B is not an option to emulate optional parameters, because it is equivalent to "forget about using default parameters, always pass all the arguments". The A option, on the other hand, lets you emulate optional parameters "on the cheap": by adding an overload that passes the optional parameter explicitly you get the functionality that you want.

    The ugly part about option A is that the number of required overloads is equal to the number of optional parameters, so if you have three or four optional parameters, you would need two or three overloads.

    Of course another option that is not truly equivalent is using a function with variable number of parameters. The problem with that approach is that once the types of your optional parameters start to diverge, you need to drop the compile-time type safety, which is rather undesirable.