使用可选参数实现向后兼容性是一个好主意吗? [英] Is using optional parameters for backwards compatibility a good idea?

查看:76
本文介绍了使用可选参数实现向后兼容性是一个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何通过使用可选参数来提供向后兼容性.

I was wondering about providing backwards compatibility by using optional parameters.

在我的程序中,我有一个接口,该接口具有一个功能,该功能在我的程序以及许多单元测试中都使用.对于某些新功能,必须将布尔值传递给此函数,如果将其设置为false,它将改变其行为.如果传递true,您将获得与以前相同的行为.

In my program I have an interface with a function that is used throughout my program as well as in a lot of unittests. For some new functionality, a boolean has to be passed into this function which will alter its behaviour if set to false. If you pass in true, you will get the same behaviour as before.

现在,我必须在当前代码中以前调用过此函数的任何地方传递true.这就是为什么我在想:好吧,我只是将true设置为布尔值的默认值.然后,我只需要在需要新行为的几个新地方传递false即可."

Now I have to pass in true everywhere where in my current code where I have called this function before. That is why I was thinking: "Ok I just put true as the default value of the boolean. Then I only have to pass in false in the few new places where I need the new behaviour."

但是,我觉得我以这种方式制作界面的动机是必须减少 now 的编码.通常,当这是唯一的动机时,我可以想到这是一条捷径,以后可能会咬我.我以后再也不会想到会导致问题的原因,这就是为什么我在这里发布此问题.

I feel however, that my motivation to make the interface this way is to have to do less coding now. Usually when that is the only motivation I can think of it is a short-cut and will probably bite me later on. I cannot think of anything that will cause problems later on though, which is why I post this question here.

除了上述情况之外,一般来说,为向后兼容(例如,在第三方使用的接口中)使新参数为可选参数是一个好主意吗?

Next to my situation as I described above, is it a good idea in general to make a new parameter optional for backwards compatibility (e.g. in interfaces that are used by third parties)?

谢谢.

推荐答案

我反对的一个很好的理由是,可选参数默认值仅在编译时使用(使用dynamic关键字时除外).

I good reason against would be that optional parameters default values are only used at compile time (except when using the dynamic keyword).

因此,如果您的第三方尝试使用新版本而不重新编译其代码(例如将您的库标记为nuget中的依赖项),那么它将不兼容,因为签名具有额外的参数.

So if your third party is trying to use the new version without recompiling their code (such as having your library marked as a dependency in nuget) it would not be compatible because the signature has an extra parameter.

这篇关于使用可选参数实现向后兼容性是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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