当方法有太多参数? [英] When a method has too many parameters?

查看:109
本文介绍了当方法有太多参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在调试一些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:


  • 代码辅助/悬停没有' t规模很好。我正在使用Eclipse,并且该方法的工具提示与屏幕一样宽,并且跨越多行。

  • 我不得不从先前的xml捕获中复制参数值,这实际上是不可能的要记住我在哪里 - 当我将光标放在逗号之后并输入一些值之前,我经常得到错误的数据类型 - 我输入的是Integer而不是String,反之亦然。

  • 即使我写了所有参数,我仍然有一些错误,签名不匹配。不幸的是,Eclipse将整个行标记为红色,因为有错误,所以找出错误花费的时间更多:(

所以这个让我思考,您认为方法的最大参数数量是多少?如果您可以更改此Web服务签名,您认为如何改进它?

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叔叔Bob Martin在清洁代码建议最多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:


  • 封装了许多相关的段落米成一个物体(例如而不是字符串surName,字符串firstName,字符串streetAddress,字符串phoneNumber 传递一个 Person 对象包含这些作为字段)

  • 在调用此方法之前在构造函数或其他方法调用中传递参数

  • encapsulate many related parameters into a single object (e.g. instead of String surName, String firstName, String streetAddress, String phoneNumber pass a Person object containing these as fields)
  • pass parameters in the constructor or other method calls prior to the invocation of this method

这篇关于当方法有太多参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆