7

嗨 Stackoverflow 社区,

我正在编写一些代码,其中将可选标准标准列表提交给我的 dao。方法签名包含 +/- 10 个参数的列表,我真的不喜欢并想重新格式化。另外,我想避免仅仅因为我添加/删除一个标准就必须重构来自不同层的所有方法签名

List searchParams(String name, Long countryCode, ...){
...
}

会成为

List searchParams(HashMap<String,Object> map) {
    BeanUtils.populate(this,map);
    ...
}

我有点担心这种情况会发生,因为这是一种不好的做法,因为我放弃了对地图中传递的内容的控制,从而给了我这种灵活性?所以我的问题是我是否走在正确的道路上?

4

4 回答 4

14

当我遇到这样的情况时,我倾向于创建一个Params类并传递。好处是:

  • 与使用 a 时不同Map,您可以拥有有意义的 getter/settings、适当的验证等;
  • 它是类型安全的和自描述的(这意味着很容易找到可用的参数及其类型)。
  • 您可以添加新参数而无需重构任何中间层。
于 2012-05-22T20:51:26.877 回答
2

您可以定义一个新类来保存/处理您的参数集,因此您可以获得比 HashMap 给您更多的控制权。写起来很烦人,或者至少很乏味,但似乎在灵活性和控制之间取得了更好的平衡。

于 2012-05-22T20:51:04.363 回答
2

您可以查看您的参数,看看您是否可以将它们作为一个逻辑组包装到一个对象中。例如,国家代码的名称可以是人员对象

public Person {
    private String name;
    private String countryCode;
}

然后,您只需将这个对象向下传递,并可以使用 getter 来获取数据,这应该比需要知道HashMap多层上的所有键更容易阅读和维护。

于 2012-05-22T20:51:19.043 回答
2

唯一适合使用映射的情况是在设计工厂时,需要将不同类型的参数传递给正在创建的不同类。在所有其他情况下,首选具有专用参数信息类的解决方案。

For an example of where passing a map is appropriate, look at the DriverManager.getConnection method: this method needs to pass parameters to constructors of driver-specific implementations of the Connection being created, so it wraps a map into Properties, and lets the user pass it through to the driver-specific connection. Note that DriverManager does not have another solution that would be future-proof.

I would strongly discourage using a map in all other cases: the added flexibility shifts error detection from compile-time to run-time, which has a strong potential of multiplying your headache beyond belief.

于 2012-05-22T21:00:31.690 回答