它是不好的做法,使二传手回报"本"? [英] Is it bad practice to make a setter return "this"?

查看:118
本文介绍了它是不好的做法,使二传手回报"本"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是个好或坏的主意,以在Java回报二传手这个?

Is it a good or bad idea to make setters in java return "this"?

public Employee setName(String name){
   this.name = name;
   return this;
}

此模式可能是有用的,因为你可以链接setter方法​​是这样的:

This pattern can be useful because then you can chain setters like this:

list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));

而不是这样的:

Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);

...但它那种违背标准约定。我想这可能是值得的,只是因为它可以使二传手做别的事情非常有用。我已经看到了使用一些地方(如JMock的,JPA)这种模式,但似乎并不常见,一般只用于非常明确的API,其中这种模式到处被使用。

...but it sort of goes against standard convention. I suppose it might be worthwhile just because it can make that setter do something else useful. I've seen this pattern used some places (e.g. JMock, JPA), but it seems uncommon, and only generally used for very well defined APIs where this pattern is used everywhere.

更新:

我所描述显然是有效的,但我所真正需要的是这是否是普遍接受的一些想法,如果有任何缺陷或相关的最佳实践。我知道了Builder模式,但它是一个涉及多一点,然后我所描述 - 作为乔希布洛赫描述它有对象创建一个相关的静态生成器类

What I've described is obviously valid, but what I am really looking for is some thoughts on whether this is generally acceptable, and if there are any pitfalls or related best practices. I know about the Builder pattern but it is a little more involved then what I am describing - as Josh Bloch describes it there is an associated static Builder class for object creation.

推荐答案

我不认为有什么特别不对的地方,它只是一个风格问题。这是很有用:

I don't think there's anything specifically wrong with it, it's just a matter of style. It's useful when:


  • 您需要同时设置多个领域(包括在建)

  • 您知道你需要设置的时候你写了code,以及哪些领域

  • 有为此许多不同的组合字段,你要设置。

替代这种方法可能是:


  1. 一个大型构造(缺点:您可以通过大量的空或默认值,而且它变得很难知道哪个值对应的)

  2. 若干重载的构造函数(缺点:一旦你有以上几个得到笨拙)

  3. 工厂/静态方法(缺点:同重载的构造函数 - 获取笨重一旦有以上几个)

如果你只在一个时间来设置一些属性我会说这是不值得返回'这个'。这当然倒下,如果你以后决定,否则返回的东西,就像一个状态/成功指示器/消息。

If you're only going to set a few properties at a time I'd say it's not worth returning 'this'. It certainly falls down if you later decide to return something else, like a status/success indicator/message.

这篇关于它是不好的做法,使二传手回报"本"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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