Suvarna Garge (Editor)

Method chaining

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results. Local variable declarations are syntactic sugar because of the difficulty humans have with deeply nested method calls. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.

Contents

A similar syntax is method cascading, where after the method call the expression evaluates to the current object, not the return value of the method. Cascading can be implemented using method chaining by having the method return the current object itself. Cascading is a key technique in fluent interfaces, and since chaining is widely implemented in object-oriented languages while cascading isn't, this form of "cascading-by-chaining by returning this" is often referred to simply as "chaining". Both chaining and cascading come from the Smalltalk language.

While chaining is syntax, it has semantic consequences, namely that requires methods to return an object, and if implementing cascading via chaining, this must be the current object. This prevents the return value from being used for some other purpose, such as returning an error value.

Scala

A paradigm in functional programming is immutability in method chaining

Java

The following is an example in Java of how method chaining might be implemented and used:

By contrast, here is a non-chained equivalent:

jQuery

jQuery relies heavily on chaining. This makes it easy to call several methods on the same selection. It also makes code more clear and prevents executing the same selection several times (hence improving performance). The following code exemplifies only its usage (and not its implementation which is in charge of jQuery):

C++

The named parameter idiom can be expressed in C++ as follows:

ObjectPascal (Dephi)

Method chaining can be expressed in ObjectPascal as follows:

Ruby

In Ruby, the named parameter idiom can be expressed as follows:

PHP

Implementation and usage of method chaining in PHP:

References

Method chaining Wikipedia