让 setter 返回“this"是不好的做法吗? [英] Is it bad practice to make a setter return "this"?

查看:40
本文介绍了让 setter 返回“this"是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让java中的setter返回this"是好还是坏?

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);

...但它有点违反标准约定.我想这可能是值得的,因为它可以让那个 setter 做一些其他有用的事情.我已经看到这种模式在一些地方使用过(例如 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 模式,但它比我所描述的要复杂一些 - 正如 Josh Bloch 描述的那样,有一个关联的静态 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:

  • 您需要一次设置多个字段(包括在构造时)
  • 您在编写代码时就知道需要设置哪些字段,并且
  • 您要设置的字段有多种不同的组合.

此方法的替代方法可能是:

Alternatives to this method might be:

  1. 一个大型构造函数(缺点:您可能会传递大量空值或默认值,并且很难知道哪个值对应于什么)
  2. 几个重载的构造函数(缺点:一旦有多个就会变得笨拙)
  3. 工厂/静态方法(缺点:与重载构造函数相同 - 一旦有多个就会变得笨拙)

如果您一次只设置几个属性,我会说不值得返回this".如果您稍后决定返回其他内容,例如状态/成功指示器/消息,它肯定会失败.

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.

这篇关于让 setter 返回“this"是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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