javaoopdesign-patterns

Is it bad practice to make a setter return "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;
}

This pattern can be useful because then you can chain setters like this:

list.add(new Employee().setName("Jack Sparrow").setId(1).setFoo("bacon!"));

instead of this:

Employee e = new Employee();
e.setName("Jack Sparrow");
...and so on...
list.add(e);

...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.

Update:

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.


Solution

  • 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. One mega constructor (downside: you might pass lots of nulls or default values, and it gets hard to know which value corresponds to what)
    2. Several overloaded constructors (downside: gets unwieldy once you have more than a few)
    3. Factory/static methods (downside: same as overloaded constructors - gets unwieldy once there is more than a few)

    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.