方法调用中的参数过多
最近,当我尝试编写有关请求参数数量的类时,我感到很困惑。
一个非常简单的构造函数示例:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将 4 个以上的参数传递给任何方法或构造函数都不是一个好主意或一个好的设计。
我记得 Joshua Bloch (Effective Java) 推荐 构建器模式针对这种情况(第 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)