Design: Java and returning self-reference in setter methods

This is called a Fluent Interface, for reference.

Personally, I think it's a pretty neat idea, but a matter of taste really. I think jQuery works this way.


I find this to be in poor style when used in setters. Immutable classes are usually a better fit for chaining, such as:

aWithB = myObject.withA(someA).withB(someB);

where myObject is of this class:

class MyClass {
    withA(TypeA a) {
         this.a.equals(a) ? this : new MyClass(this, a);
    }

    private MyClass(MyClass copy, TypeA a) {
        this(copy);
        this.a = a;
    }
}

The builder pattern is also useful, since it allows the final object to be immutable while preventing the intermediate instances you would normally have to create when using this technique.


@pek
Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return this. If you're interested in this topic, there is a bunch of links and a simple example on Alex Miller's Java 7 page.


I wouldn't do it myself, because to me it muddies what a particular method does, and the method-chaining is of limited use to me over doing it longhand. It isn't going to send me into a quivering ball of rage and psychosis, though, which is always a good thing. :')

I wouldn't be concerned about performance; just ask Knuth.

Tags:

Java