|
|
Method chainingThe term method chaining refers to both a design and a convention. It applies to classes and methods where:
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:
Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved. |