Allow method chaining for fluent APIs

By Steve Claridge on 2014-03-15.

Method chaining means being able to call multiple methods of an object whilst not having to respecify the owning object on each call. Assume we have an object with three methods, one(), two() and three() - assuming you wanted to call all three methods you would normally do this:

MyObject m = new MyObject();
m.one();
m.two();
m.three();

With method chaining it would look like this:

MyObject m = new MyObject().one().two().three();

Kinda neat! This technique is used a lot in Javascript and it's seen throughout jQuery. Method-chaining creates easy to use APIs and shorter, cleaner code. To implement this in your objects is actually very easy, all you need to do is to return the Object from your setter methods. For example, a simple Java class with some setters:

class Stuff
{
  private String _one;
  private String _two;    public void setOne( String o )
  {
    _one = o;
  }
  public void setTwo( String t )
  {
    _two = t;
  }
} Stuff s = new Stuff();
s.setOne( "one" );
s.setTwo( "two" );

It's pretty standard to return void from setter methods. But if you change them to return Stuff then you can chain the setters.

class Stuff
{
  private String _one;
  private String _two;    public Stuff one( String o )
  {
    _one = o;
    return this;
  }
  public Stuff two( String t )
  {
    _two = t;
    return this;
  }
} Stuff s = new Stuff().one( "one" ).two( "two" );