将许多参数传递给方法的最佳实践? [英] Best practice for passing many arguments to method?

查看:180
本文介绍了将许多参数传递给方法的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

偶尔,我们必须编写接收许多参数的方法,例如:

Occasionally , we have to write methods that receive many many arguments , for example :

public void doSomething(Object objA , Object objectB ,Date date1 ,Date date2 ,String str1 ,String str2 )
{
}

当我遇到这种问题时,我经常将参数封装到地图中。

When I encounter this kind of problem , I often encapsulate arguments into a map.

Map<Object,Object> params = new HashMap<Object,Object>();
params.put("objA",ObjA) ;

......

public void doSomething(Map<Object,Object> params)
{
 // extracting params 
 Object objA = (Object)params.get("objA");
 ......
 }

这不是一个好习惯,将params封装到地图中完全是浪费效率。
好​​的方面是,干净的签名,很容易添加其他参数,修改最少。
这类问题的最佳做法是什么?

This is not a good practice , encapsulate params into a map is totally a waste of efficiency. The good thing is , the clean signature , easy to add other params with fewest modification . what's the best practice for this kind of problem ?

推荐答案

有效的Java ,第7章(方法),第40项(设计方法签名仔细),Bloch写道:

In Effective Java, Chapter 7 (Methods), Item 40 (Design method signatures carefully), Bloch writes:

有三个缩短过长参数列表的技巧:

There are three techniques for shortening overly long parameter lists:


  • 将方法分解为多个方法,每个方法只需要一部分参数

  • 创建辅助类来保存参数组(通常是静态成员类)

  • 使Builder模式从对象构造适应方法调用。

有关详细信息,我建议您购买该书,这非常值得。

For more details, I encourage you to buy the book, it's really worth it.

这篇关于将许多参数传递给方法的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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