Method Chaining

Method chaining is a simple programming technique that can be implemented in almost any programming language. In simple words, it means that a method performs some operations on “this” object and then returns it so it can be used further more. It allows us to invoke several methods one after another, on one or different objects, usually written in the same line.

For example we can build a rectangle class using using the Method Chaining for setters. You can see the setters are a little bit different than regular setters:

class ChainedRectangle
    protected int x;
    public ChainedRectangle setX(int x) { this.x = x; return this; }

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

    protected int width;
    public ChainedRectangle setWidth(int width) { this.width = width; return this; }

    protected int height;
    public ChainedRectangle setHeight(int height) { this.height = height; return this; }

    protected String color;
    public ChainedRectangle setColor(String color) { this.color = color; return this; }

Then if we need to build a rectangle we can write a single line for setting all the required values:

new         Rectangle().setX(10).setY(10).setWidth(13).setHeight(15).setColor("red");

Along with autocomplete option in most of todays IDEs method chaining might provide a suggestive way of doing some actions in less code.
Continue reading