何时使用方法重载 VS “请求” 目的

发布于 2024-07-12 12:42:26 字数 1431 浏览 6 评论 0原文

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

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

发布评论

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

评论(2

高跟鞋的旋律 2024-07-19 12:42:26

使用 MakePancakes(PancakeOptions options) 的真正优点是您可以更改 PacakeOptions 的属性数量,而无需更改方法实现。 当参数的数量可以改变或者是可选的时,它会很有帮助。 以这种方式表示配置/属性/选项确实有意义。

但我不认为它可以替代重载方法。

一些经验法则:

  • 如果一个方法有超过 5 个参数,那么它可能会做不止 1 件事。 我会审查该方法并尝试将其拆分为更具体的函数。

  • 方法的所有属性都是必需的(即不能为 null)

The real advantage of using MakePancakes(PancakeOptions options) is that you can change the number of attributes of PacakeOptions without having to change the method implementation. It can be helpful when the number of parameters can change or are optional. It does make sense to represent configuration/properties/options this way.

But I don't think it is a replacement for overloading methods.

Some rule of thumb:

  • if a method has more than 5 arguments, then it is probably doing more than 1 thing. I would review the method and try to split it in more specific functions.

  • All attributes of a method are required (i.e. cannot be null)

紫﹏色ふ单纯 2024-07-19 12:42:26

在创建请求类型或枚举之前,我自己不需要很多重载(枚举数组似乎是一个非常简单的请求对象)。 也许3-4? 有些框架方法有 9-10 个重载,我发现这有点烦人,但我认为这更像是一个风格问题。

I wouldn't need many overloads myself before I created a request type or enum (array of enum seems like a pretty simple request object). Maybe 3-4? Some framework methods have 9-10 overloads and I find that to be a bit annoying but this is more of a style question I think.

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