扩展现有的API:使用默认参数还是包装函数? [英] Extend an existing API: Use default argument or wrapper function?

查看:86
本文介绍了扩展现有的API:使用默认参数还是包装函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的方法(或一般的函数),我需要增加其他功能,但是我不想破坏代码中其他地方对该方法的使用.示例:

I have an existing method (or function in general) which I need to grow additional functionality, but I don't want to break any use of the method elsewhere in the code. Example:

int foo::bar(int x)
{
 // a whole lot of code here
 return 2 * x + 4;
}

在代码库中被广泛使用.现在,我需要将4设置为参数,但是任何已经调用foo :: bar的代码仍应收到期望的代码.我应该扩展并重命名旧方法,然后将其包装到新的方法中吗

is widely used in the codebase. Now I need to make the 4 into a parameter, but any code that already calls foo::bar should still receive what it expects. Should I extend and rename the old method and wrap it into a new one like

int foo::extended_bar(int x, int y)
{
 // ...
 return 2 * x + y;
}

int foo::bar(int x)
{
 return extended_bar(x,4);
}

或者我应该在头文件中声明默认参数,例如

or should I declare a default argument in the header file like

int bar(int x, int y=4);

只需扩展功能

int foo::bar(int x, int y)
{
 // ...
 return 2 * x + y;
}

每个变体的优点和缺点是什么?

What are advantages and disadvantages of each variant?

推荐答案

我通常使用 wrapper函数(大多数情况下通过重载)代替默认参数.

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

原因是向后兼容有两个级别:

  1. 具有 source-level 的向后兼容性意味着您必须重新编译调用代码,而无需进行更改,因为新的功能签名与旧的功能签名兼容.两者都可以达到这个水平.默认值和包装器/重载.

  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.

更强的级别是 binary-level 的向后兼容性,即使不重新编译也可以正常工作,例如当您无权访问调用代码时.假设您以二进制形式(例如在DLL等中)部署函数.在这种情况下,签名必须完全相同才能正常工作,而默认值则不是这种情况-它们会破坏这种兼容性水平.

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.

这篇关于扩展现有的API:使用默认参数还是包装函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆