使用可选参数来实现向后兼容性是一个好主意吗?

发布于 2024-12-05 20:15:02 字数 511 浏览 0 评论 0 原文

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

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

现在,我必须在当前代码中之前调用过此函数的所有位置传递 true 。这就是为什么我在想:“好吧,我只是将 true 作为布尔值的默认值。然后我只需要在我需要的几个新地方传入 false 即可。需要新的行为。”

然而,我觉得我以这种方式制作界面的动机是现在必须减少编码。通常,当这是我能想到的唯一动机时,它就是一条捷径,并且可能会在以后咬我。不过,我想不出有什么会在以后引起问题的,这就是我在这里发布这个问题的原因。

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

提前致谢。

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

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.

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."

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)?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她比我温柔 2024-12-12 20:15:02

我反对的充分理由是可选参数默认值仅在编译时使用(除非使用动态关键字)。

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文