Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setters returning the instance reference. Pattern or anti-pattern?

I was thinking about code structure, and thinking about setters. These used to be void methods, so why don't use some possible return value, to enable some new code structure?

My idea was to change all the properties setters from void to an instance reference, so we can do setters sequentially, or something else. Here is an example:

public class MyClass {
    private int foo;
    private String bar;

    public MyClass setFoo(int foo) {
        this.foo = foo;
        return this;
    }

    public MyClass setBar(String bar) {
        this.bar = bar;
        return this;
    }

}

Then in some other place in the code we could do:

...
MyClass myInstance = new MyClass();
myInstance.setFoo(auxFoo).setBar(auxBar);
...

This allow to set all of class properties in a single line, useful in transformation methods.

Or even:

...
return myInstance.setFoo(auxFoo);

This one was my goal, to be able for example to set an error property, while returning it. This can simplify a catch block, for instance.

EDIT: After some answers I need to add:

  • The question is just about setters (not about doing this in all methods), and not restricted to chaining, but to other usages like the return example.
  • Could the change from void to something else create any problem? JavaBeans Introspection, for instance.
  • Can you see any more advantage or disadvantage of doing this?

I was hoping to see some discussion.

like image 295
lpinto.eu Avatar asked Oct 06 '11 10:10

lpinto.eu


2 Answers

It's a common technique, known as Method Chaining. Hibernate uses it in its Criteria classes, and is present in other popular frameworks, such as Wicket.

Generally, you've got to be careful and apply it in those void methods that you're sure that will never need to return anything. And you shouldn't be using it in your Java Beans, as it has been already discussed in this question: Does Java bean's setter permit return this?.

See this related SO question for some tips and drawbacks that may be useful while using this pattern.

like image 67
Xavi López Avatar answered Nov 13 '22 10:11

Xavi López


This is quite common practice and definitely a pattern - not an anti-pattern. It is more commonly referred to as :

http://en.wikipedia.org/wiki/Fluent_interface

and

http://en.wikipedia.org/wiki/Method_chaining

Some excellent libraries make use of it : jQuery and joda-time.

You can also specify when the chain ends by using an end method that does not return anything, or does something else entirely - in the case of an inner static builder it calls a constructor.

For what its worth I really like it.

like image 44
NimChimpsky Avatar answered Nov 13 '22 10:11

NimChimpsky