Question

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.

Was it helpful?

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.

OTHER TIPS

Most cases with optional parameters would involve only one or two.

For one extra parameter (or even two), it's okay to add an overloaded method as in your option "A". Code that already calls your old method doesn't need to be changed, and new code can call either one.

However, for more than 2, it becomes cumbersome, especially for independent optional variables. This requires an exponential number of overloads: 2 total for 1 optional variable, 4 total for 2 optional variables, 8 total for 3 optional variables, etc.

At that point, it's best to use one method that includes all "optional" parameters, as long as your method has a way to distinguish the values that are "not" being passed, such as a sentinel value or null.

My answer is "it depends" on how many parameters you have. If your circumstances fall into one or two extra parameters, as I think it most often does, then option A would be my choice. If you are that rare case with lots of additional parameters, then choose option B.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top