Is it bad practice to make a setter return “this”?

2020-01-25 12:18发布

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.

27条回答
Luminary・发光体
2楼-- · 2020-01-25 12:42

I prefer using 'with' methods for this:

public String getFoo() { return foo; }
public void setFoo(String foo) { this.foo = foo; }
public Employee withFoo(String foo) {
  setFoo(foo);
  return this;
}

Thus:

list.add(new Employee().withName("Jack Sparrow")
                       .withId(1)
                       .withFoo("bacon!"));

Warning: this withX syntax is commonly used to provide "setters" for immutable objects, so callers of these methods might reasonably expect them to create new objects rather than to mutate the existing instance. Maybe a more reasonable wording would be something like:

list.add(new Employee().chainsetName("Jack Sparrow")
                       .chainsetId(1)
                       .chainsetFoo("bacon!"));

With the chainsetXyz() naming convention virtually everyone should be happy.

查看更多
叛逆
3楼-- · 2020-01-25 12:43

Paulo Abrantes offers another way to make JavaBean setters fluent: define an inner builder class for each JavaBean. If you're using tools that get flummoxed by setters that return values, Paulo's pattern could help.

查看更多
Juvenile、少年°
4楼-- · 2020-01-25 12:43

Yes, I think it's a good Idea.

If I could add something, what about this problem :

class People
{
    private String name;
    public People setName(String name)
    {
        this.name = name;
        return this;
    }
}

class Friend extends People
{
    private String nickName;
    public Friend setNickName(String nickName)
    {
        this.nickName = nickName;
        return this;
    }
}

This will work :

new Friend().setNickName("Bart").setName("Barthelemy");

This will not be accepted by Eclipse ! :

new Friend().setName("Barthelemy").setNickName("Bart");

This is because setName() returns a People and not a Friend, and there is no PeoplesetNickName.

How could we write setters to return SELF class instead of the name of the class ?

Something like this would be fine (if the SELF keyword would exist). Does this exist anyway ?

class People
{
    private String name;
    public SELF setName(String name)
    {
        this.name = name;
        return this;
    }
}
查看更多
Ridiculous、
5楼-- · 2020-01-25 12:44

I have been making my setters for quite a while and the only real issue is with libraries that stick with the strict getPropertyDescriptors to get the bean reader/writer bean accessors. In those cases, your java "bean" will not have the writters that you would expect.

For example, I have not tested it for sure, but I would not be surprised that Jackson won't recognizes those as setters when creating you java objects from json/maps. I hope I am wrong on this one (I will test it soon).

In fact, I am developing a lightweight SQL centric ORM and I have to add some code beyong getPropertyDescriptors to recognized setters that returns this.

查看更多
地球回转人心会变
6楼-- · 2020-01-25 12:45

At least in theory, it can damage the optimization mechanisms of the JVM by setting false dependencies between calls.

It is supposed to be syntactic sugar, but in fact can create side effects in the super-intelligent Java 43's virtual machine.

That's why I vote no, don't use it.

查看更多
聊天终结者
7楼-- · 2020-01-25 12:45

This particular pattern is called Method Chaining. Wikipedia link, this has more explanation and examples of how it's done in various programming languages.

P.S: Just thought of leaving it here, since I was looking for the specific name.

查看更多
登录 后发表回答