2

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.

tamasd
  • 5,747
  • 3
  • 25
  • 31
  • possible duplicate of [Is it bad practice to make a setter return "this"?](http://stackoverflow.com/questions/1345001/is-it-bad-practice-to-make-a-setter-return-this) – Femaref Feb 01 '11 at 23:43

1 Answers1

1

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.

staticsan
  • 29,935
  • 4
  • 60
  • 73