0

An automatically generated setter in some popular IDEs may look like this:

public class Person {
    private String name;

    public String getName() {
        return name;
    }

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

Is there any disadvantage at all to doing the following?

public class Person {
    private String name;

    public String getName() {
        return name;
    }

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

If not, why is it not more widespread? The advantage of being able to chain commands together seems very convenient at first glance. Thank you in advance for your insights.

WonderfulWorld
  • 439
  • 4
  • 11
  • See http://stackoverflow.com/questions/1345001/is-it-bad-practice-to-make-a-setter-return-this – ROMANIA_engineer Oct 29 '16 at 22:20
  • I vaguely remember both Eclipse and IntelliJ giving the option to do this "Builder Patter", is what it is called. – OneCricketeer Oct 29 '16 at 22:20
  • 2
    Because that's not how a setter is defined in the Java bean specification, on which many, many Java technologies and frameworks rely. – JB Nizet Oct 29 '16 at 22:21
  • There is a whole bunch of setters in Java NIO that do exactly that. – user207421 Oct 30 '16 at 00:35
  • @EJP but AFAIK those are not following the get/set name convention. Thanks for pointing this out, now I finally understood why their names are like that. – MauganRa Feb 23 '17 at 19:02

0 Answers0