方法调用中的参数过多

发布于 2024-10-10 15:34:06 字数 470 浏览 0 评论 0原文

最近,当我尝试编写有关请求参数数量的类时,我感到很困惑。

一个非常简单的构造函数示例:

Burger(bun, meat, cheese, lettuce)
    this.bun = bun
    this.meat = meat
    ...

Vs

Burger(grocery)
    this.bun = grocery.bun
    this.meat = grocery.meat
    ...

两种方法都是有效的方法。第一种方法准确地显示了汉堡中的内容,将参数分解为更通用的类,从而减少了耦合,而且我认为通常更容易测试,因为对象图更简单。

但第二种方法更简单、更干净,而且汉堡可能需要更多的原料,那么第一种方法的争论就会极大地膨胀。

我想知道在这种情况下,推荐哪种方式?寻求更简洁但更耦合的代码,或者更冗长的方式。

Lately I've been torn when trying writing classes regarding the number of parameters requested.

A very simple constructor example:

Burger(bun, meat, cheese, lettuce)
    this.bun = bun
    this.meat = meat
    ...

Vs

Burger(grocery)
    this.bun = grocery.bun
    this.meat = grocery.meat
    ...

Both ways are valid approaches. The first way shows exactly what's going into the burger, breaks down the arguments into more general classes so it makes for less coupling, and I think is generally easier to test because the object graph is simpler.

But the second way is a lot simpler, cleaner, and perhaps the burger can require a lot more ingredients, then the arguments in the first way can balloon immensely.

I'd like to know which way would be recommended in a situation like this? Go for the cleaner but more coupled code, or the more verbose way.

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

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

发布评论

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

评论(1

新一帅帅 2024-10-17 15:34:06

将 4 个以上的参数传递给任何方法或构造函数都不是一个好主意或一个好的设计。

我记得 Joshua Bloch (Effective Java) 推荐 构建器模式针对这种情况(第 2 项)

第 2 项:遇到问题时考虑构建器有许多构造函数参数

passing 4+ parameters to any method or constructor is not a good idea or a good design.

I remember that Joshua Bloch (Effective Java) recommend Builder Pattern to this situation (Item 2)

Item 2: Consider a builder when faced with many constructor parameters

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