Method chaining

The term method chaining refers to both a design and a convention. It applies to classes and methods where:

  • multiple methods are potentially going to be called on the same object;
  • the methods in question need no return value.

The idea of method chaining is that if the methods need no "useful" return value, then the method can return this (i.e. a reference to the same object on which the method is being called). Let's say we have a string buffer object with an append() method that logically looks as follows:

public class StringBuffer {
  public void append(String str) {
    // ... useful code ...
  }
}

The above method has the disadvantage that it is clumsy to append multiple strings to a buffer:

StringBuffer sb = new StringBuffer();
sb.append("Hello ");
sb.append(name);
sb.append("! Welcome!");

To allow method chaining, we instead declare the method as follows:

public class StringBuffer {
  public StringBuffer append(String str) {
    // ... useful code ...
    return this;
  }
}

Now, we can "chain" together calls to append() as follows:

StringBuffer sb = new StringBuffer();
sb.append("Hello ").append(name).append("! Welcome!");

Allowing method chaining is thus a design decision that needs to be made at the time of defining the API. Classes and methods that allow method chaining in the JDK include:

  • the append() methods of the actual StringBuffer and StringBuilder classes;
  • the Appendable interface;
  • put() methods on NIO Buffers such as ByteBuffer;
  • methods on Matcher, part of the Java regular expressions API.

Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved.