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.

For example we can write a simple class to build sql queries. Then we can invoke in a simple way.

public class Query
{
    protected String queryString = "";

    public Query select(String what) 
    {
        queryString = "SELECT " + what;
    }

    public Query from(String from)
    {
        queryString = " FROM " + from;
    }

    public Query where(String where)
    {
        queryString = " WHERE " + where;
    }

    public ResultSet Invoke()
    {
        //... database invocation bla bla
        return result;
    }
}

Then, to build the query we invoke:

new Query().select("*").from("table").where("a=b").Invoke();

One of the problems of the Method Chaining pattern is the fact that it can not ensure the order of the invoked method. In order to do that each method can return a specific interface object which implements only the allowed methods.

For example we define an interface ISelectedQuery with a single method from, IFromQuery with a single method where. ISelectedQuery.from returns and object of type IFromQuery and IFromQuery returns a Query object. All the interfaces are implemented by the Query object. That way the order of invoking the methods is ensured.

Here is how the code looks like:

public interface ISelectedQuery
{
    IFromQuery from(String from);
}

public interface IFromQuery
{
    Query where(String where);
}

 public class Query implements ISelectedQuery, IFromQuery
{
    protected String queryString = "";

    public ISelectedQuery select(String what) 
    {
        queryString = "SELECT " + what;
        return this;
    }

    public IFromQuery from(String from)
    {
        queryString = " FROM " + from;
        return this;
    }

    public Query where(String where)
    {
        queryString = " WHERE " + where;
        return this;
    }

    public ResultSet Invoke()
    {
        //... database invocation bla bla
        return result;
    }
}

The above code ensure that only the right methods can be invoked. Further more the syntax autocomplete option from most of today IDEs will show in the drop down only the right method(s).

Did you enjoy this tutorial? Be sure to subscribe to the my RSS feed not to miss my new posts!
... or make it popular on

11 Comments

  1. A good post. I liked the SQL query builder example. Might even come handy one day. To make it happen one must have very clear requirements from the beginning, as later changes would prove costly. Some would consider this as a demerit.

  2. If I understood correctly you can do this

    new Query().where(“a=b”).Invoke();

    because Query implements all those interfaces and after new Query() you can pick any method you like and skip some methods (e.g. select)

    I think it would be better to provide some satic factory method that returns ISelectedQuery so you will be sure that all methods ar invoked.

    Query.select(“*”).from(“table”).where(“a=b”).invoke();

  3. thanks @GHad. You’re right a factory would be better in some real scenario. However, if we need a query object on which we can do selects/inserts/updates we can put all the methods in a single class, or to create several classes for each action. This is just a simple example of method chaining.

    I’ve also changed the example and the query class implements now the interfaces.

  4. While I really like the clarity and efficiency of this method, I’m still having a hard time convincing myself that the loss of clarity in the class design is worth it. The last example has a lot of code overhead to ensure method chaining works and the changing return types would confuse someone not familiar with the class or chaining.

    Also imagine how confusing the last class example would be if it were 5-8 methods long (add in some and() and between() methods for example) and how hard it would be to intuitively determine the chain order with multiple elements at the same level. (Try to add in all SQL constructs into the Query class and you’ll see what I mean.)

  5. I agree it’s not something you should use every day due to the overhead and class design unorthodox views. However, it’s a good exercise to know about it.

    I also think it a great way to expose simple api’s. Just imagine you have to use some api where you just put a dot and the available methods are displayed so you can select the desired one. And the Method Chaining will help you to validate the logic and order of methods invoked at compile time.

  6. Good examples. I’ve always liked the way JQuery does the method chaining. It’s the quickest way to call functions, as there is no need to store the intermediate result objects in temperory variable.

  7. Nice explanation, fyi this is know as the ‘fluent interface’ pattern or ‘builder pattern’ depending how you look at it.

Leave a Comment.