|
|
This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. (May 2008) |
Method chaining is a common technique for invoking multiple method calls in object-oriented programming languages. Each method returns an object (possibly the current object itself), allowing the calls to be chained together in a single statement.[1] A method chain is also known as a train wreck due to an increasing amount of methods stacked after another in one line.[2]
Method chaining is not required. It only potentially improves readability and reduces the amount of source code. It is the core concept behind building a fluent interface.
|
Contents
|
The following is an example in Java of how method chaining might be implemented and used:
class Person { private String name; private int age; // In addition to having the side-effect of setting the attributes in question, // the setters return "this" (the current Person object) to allow for further chained method calls. public Person setName(String name) { this.name = name; return this; } public Person setAge(int age) { this.age = age; return this; } public void introduce() { System.out.println("Hello, my name is " + name + " and I am " + age + " years old."); } // Usage: public static void main(String[] args) { Person person = new Person(); // Output: Hello, my name is Peter and I am 21 years old. person.setName("Peter").setAge(21).introduce(); } }
By contrast, here is a non-chained equivalent:
class Person { private String name; private int age; // Per normal Java style, the setters return void. public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void introduce() { System.out.println("Hello, my name is " + name + " and I am " + age + " years old."); } // Usage: public static void main(String[] args) { Person person = new Person(); // Not using chaining; longer than the chained version above. // Output: Hello, my name is Peter and I am 21 years old. person.setName("Peter"); person.setAge(21); person.introduce(); } }
This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)