7/07/2011

Chained Invocation

Chained invocation is a matter of language design actually. I first saw this type of invocation in the Rest-assured library. I will not introduce library here, maybe later.

You know java setter methods are void functions. By using chained invocation, we may use void-setters as a builder, simply returning the object (this) in every setter. Idea is simple but very useful. Also chained invocation is not for setters only, every void function can implement the logic for the readability of the code.

Below there is a simple class with some void setters.
class Simple {

    int x;
    int y;

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getY() {
        return y;
    }

}

This class can be instantiated in the code by this way:
Simple s = new Simple();
s.setX(4);
s.setY(5);

Instead, we can change the class to the following by just manipulating the setters. And the usage will be readable.
class Simple {

    int x;
    int y;

    public Simple setX(int x) {
        this.x = x;
        return this;
    }

    public int getX() {
        return x;
    }

    public Simple setY(int y) {
        this.y = y;
        return this;
    }

    public int getY() {
        return y;
    }

}

We can use it in the code:
Simple s = new Simple();
s.setX(4).setY(5);

We have done the following:
  • Change the return type 'void' of the setters to the class type itself
  • Add 'return this' to the last line of each setter

Maybe the example is not suitable, but the logic.

Ref: A proposal from the Matthias Ernst
Java 7 features/exclusions on Pure Danger Tech