Extend an existing API: Use default argument or wrapper function?

徘徊边缘 提交于 2019-12-06 06:04:17

I usually use a wrapper function (via overloading most of the time) instead of default parameters.

The reason is that there are two levels of backward compatibility:

  1. Having source-level backward compatibility means that you have to recompile the calling code without changes, because the new function signatures are compatible to the old ones. This level can be achieved with both; default values and wrappers/overloading.

  2. A stronger level is binary-level backward compatibility, which even works without recompilation, e.g. when you don't have access to the calling code. Imagine you deploy your function in binary form, like in a DLL, etc. In such a case, the signatures have the be exactly the same to make it work, which is not the case for default values - they will break this level of compatibility.

Another advantage of wrapper functions is - if your application has logging of any kind - you can dump out a warning in the old function that it will become obsolete in future versions and that it is recommended to use the new one.

The longer I use C++, the less I like default function parameters. I can't pinpoint any specific reason for my dislike, but I find that if I use them, I almost always end up removing them later. So my (subjective) vote goes for the new named function - the name could of course be same as that of the old one.

I personally believe that implicit behaviors are (one of) the roots of all evil.

Anything that obfuscates for a maintainer or caller the identity of the target being invoked should have a very strong justification, especially if it is part of a major API.

Therefore, I would argue strongly against the option with the default operation.

In addition, I believe that if a certain function can be invoked with a different number of parameters, then there is something inherently different both versions of the function or they are doing too much. The distinction should probably be in the name, and should probably be more meaningful than "_extended"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!