Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with default values in (deeply) nested function calls?

Suppose there is a function with a default value:

int foo(int x=42);

If this is called by others like this:

int bar(int x=42) { return foo(x); }
int moo(int x=42) { return bar(x); }

This is of course just a contrived example. However, I sometimes have a quite similar situation. The parameter is just passed from the highest level (moo) to the lowest and only there it is actually used. The bad thing about this is that when I change foo to have a default different than 42 I would have to search for all callers and change the default value accordingly.

Is there some pattern/idiom to avoid this situation?

The only simple solution that comes to my mind is

int bar()      { return foo(); }
int bar(int x) { return foo(x); }

However, as I am a bit lazy and in real code this would lead to quite some code duplication, I would like to avoid this.

like image 225
463035818_is_not_a_number Avatar asked Jul 19 '16 13:07

463035818_is_not_a_number


People also ask

Why to use default parameters?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

What is the purpose of declaring a default value inside the argument of a function?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

Why will you use default parameters in JavaScript?

In JavaScript, default function parameters allow you to initialize named parameters with default values if no values or undefined are passed into the function.


1 Answers

I'd advise to select one of these two options below (as you can see in other answers - there are more possible solutions).

  1. Overload your functions
  2. Define constant

So, option 1 would looks like below:

int foo(int x=42);
int bar(int x) { return foo(x); }
int moo(int x) { return bar(x); }
int bar() { return foo(); }
int moo() { return bar(); }

And, option 2 will be a little shorter:

constexpr int FOO_DEFAULT = 42;
int foo(int x=FOO_DEFAULT);
int bar(int x=FOO_DEFAULT) { return foo(x); }
int moo(int x=FOO_DEFAULT) { return bar(x); }

I'd use option-1 for cases with small number of default values (like one default value), option-2 for cases where you have quite a few default values - like foo(int a, int b = 3, std::string c = "wow", float pi = 3.14)

like image 171
PiotrNycz Avatar answered Nov 14 '22 21:11

PiotrNycz