Recently the following was added to the VTK coding conventions document:
- Prefer overloading functions to default arguments.
Rationale: Default function arguments in C++ are a tempting way to add an argument to a function while maintaining easy backwards compatibility. However, if you later want to add another argument to the list in a way that preserves backwards compatibility, it, too, must be a default argument. To supply the second of these arguments in a call forces you to also supply the first argument, even if it is the default value. As a result, this is not a clean way to add a argument to a function. Instead, function overloading should be preferred.
Iāve asked for an explanation of this rule in the merge request but it was not really answered there - no example or explanation was given. The question has also come up in this topic, so I though I would bring up this question here: How overloading is a cleaner way to add arguments to a function?
How is it even feasible to pass multiple optional arguments via overloading? Adding overloaded methods for multiple optional arguments works if you are so lucky that the all the optional arguments have incompatible types - but most of the time this is not the case. For example, if you have 2 optional float
arguments, then you can specify a method with default arguments:
void DoSomething(double a, double b=-1, double c=-1);
But how would you implement that with overloaded methods?
void DoSomething(double a);
void DoSomething(double a, double b);
void DoSomething(double a, double c); // this would throw a build error, because it is equivalent with the previous line
void DoSomething(double a, double b, double c);
There are some valid reasons for preferring overload in some cases and default value in others - see for example the discussion in Google C++ style guide, but they are not related to managing backward compatibility more cleanly.
Could we replace this guidance with something more balanced, and better explained, such as Googleās? If nobody wants to spend time with better explaining the current recommendation then thatās completely fine too, it means that it is actually not that important; but in that case the best is to simply remove the recommendation to keep things simpler and avoid unnecessary discussions. I would just want to avoid having some questionable rules in the VTK coding conventions, because that could lead to developers not taking the entire document seriously.