链接设置器:有缺点吗?
我已经开始在我的设置器中使用一种从 jQuery 中采用的技术,称为链接。示例:
class Foo {
private int bar;
private int baz;
public int getBar() { return this.bar; }
public int getBaz() { return this.baz; }
public Foo setBar(int bar) {
this.bar = bar;
return this;
}
public Foo setBaz(int baz) {
this.baz = baz;
return this;
}
}
我更喜欢这种方式,因为它可以非常轻松地设置多个属性。
有缺点吗?我曾就此询问过几位 Java 程序员,但他们只能说这“不好”,但他们无法给我一个正确的解释。
I have started using a technique, adopted from jQuery, called chaining in my setters. Example:
class Foo {
private int bar;
private int baz;
public int getBar() { return this.bar; }
public int getBaz() { return this.baz; }
public Foo setBar(int bar) {
this.bar = bar;
return this;
}
public Foo setBaz(int baz) {
this.baz = baz;
return this;
}
}
I prefer this way, because it makes easy to set multiple properties very easily.
Is there a drawback? I have asked several Java programmers about this, but all they could say is that it is "not nice", but they couldn't give me a proper explanation why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您遇到了一个缺点:在某些编程语言的文化中,这是不寻常且非常规的。有些文化比其他文化对不寻常和非常规的反应更好。我同意它有其优点,但 Java setter 通常不是这样编码的。
I think you've encountered one drawback: in the culture of some programming languages, it is unusual and unconventional. And some cultures react better than others to unusual and unconventional. I agree that it has merit, but Java setters are just not usually coded that way.