当一个方法有太多参数时? [英] When a method has too many parameters?
问题描述
今天在调试一些 Web 服务客户端代码时(在 Java 中,使用 jax-ws)我遇到了一个带有 97 个参数的令人兴奋的 Web 服务方法!
When debugging some web-service client code today (in Java, with jax-ws) I ran across a web-service method with the mind-blowing amount of 97 parameters!
我必须创建一个调用此方法的测试用例,我注意到以下几点:
I had to create a test case that calls this method, and I noticed several things:
- 代码辅助/悬停不能很好地扩展.我正在使用 Eclipse,该方法上的工具提示与屏幕一样宽,跨越多行.
- 我不得不从以前的 xml 捕获中复制参数值,而且几乎不可能记住我在哪里" - 当我将光标定位在逗号之后并且在输入某个值之前,我经常得到错误的数据类型- 我输入的是整数而不是字符串,反之亦然.
- 即使我写了所有参数,我仍然有一些错误,签名不匹配.不幸的是,Eclipse 将整行标记为红色,因为有错误,因此查找错误的位置需要更多时间:(
所以这让我想到,你认为一个方法的最大参数数量是多少?如果您可以更改此网络服务签名,您认为可以如何改进?
So this got me thinking, what do you think is the maximum sane number of parameters for a method? And if you could change this web-service signature, how do you think it can be improved?
推荐答案
没有明确的限制,但我对超过 3-4 个参数感到不舒服.AFAIR Uncle Bob Martin 在 Clean Code 建议最大3.
There is no clear limit, but I am uncomfortable with more than 3-4 parameters. AFAIR Uncle Bob Martin in Clean Code recommends max 3.
有几个重构可以减少方法参数的数量(参见 有效处理遗留代码,作者 Michael Feathers 了解详情).我想到了这些:
There are several refactorings to reduce the number of method parameters (see Working Effectively with Legacy Code, by Michael Feathers for details). These come to my mind:
- 将许多相关参数封装到单个对象中(例如,代替
String surName、String firstName、String streetAddress、String phoneNumber
传递一个包含这些作为字段的Person
对象) - 在调用此方法之前在构造函数或其他方法调用中传递参数
- encapsulate many related parameters into a single object (e.g. instead of
String surName, String firstName, String streetAddress, String phoneNumber
pass aPerson
object containing these as fields) - pass parameters in the constructor or other method calls prior to the invocation of this method
这篇关于当一个方法有太多参数时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!