开发者

Chaining setters: is there a drawback?

开发者 https://www.devze.com 2023-02-08 04:32 出处:网络
I have started using a technique, adopted from jQuery, cal开发者_如何学运维led chaining in my setters. Example:

I have started using a technique, adopted from jQuery, cal开发者_如何学运维led 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消