Method chaining

Programming syntax


title: "Method chaining" type: doc version: 1 created: 2026-02-28 author: "Wikipedia contributors" status: active scope: public tags: ["method-(computer-programming)", "articles-with-example-c++-code", "articles-with-example-ruby-code", "articles-with-example-java-code", "articles-with-example-php-code"] description: "Programming syntax" topic_path: "general/method-computer-programming" source: "https://en.wikipedia.org/wiki/Method_chaining" license: "CC BY-SA 4.0" wikipedia_page_id: 0 wikipedia_revision_id: 0

::summary Programming syntax ::

Method chaining 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.

Rationale

Local variable declarations are syntactic sugar.

Method chaining eliminates an extra variable for each intermediate step. The developer is saved from the cognitive burden of naming the variable and keeping the variable in mind.

Method chaining has been referred to as producing 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.{{cite book | last = Martin | first = Robert Cecil | authorlink = Robert C. Martin | title = Clean Code: A Handbook of Agile Software Craftsmanship | publisher = Prentice Hall | year = 2008 | isbn = 978-0-13-235088-4

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 " is often referred to simply as "chaining". Both chaining and cascading come from the Simula 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.

Examples

I/O streams

Main article: iostream

A common example is std::istream and std::ostream (the input and output stream classes) in C++, where for example `

::code[lang=cpp] a << b << c;

// this is equivalent to: a << b; a << c; ::

Functional programming

Main article: Functional programming

Functional programming is another example of the usage of method chaining, involving higher-order functions. In object-oriented programming, higher-order functions and manipulation of collections can be represented through methods that are chained together.{{Cite book |last=Nakamaru |first=Tomoki |author2=Matsunaga, Tomomasa |author3=Yamazaki, Tetsuro |author4=Akiyama, Soramichi |author5=Chiba, Shigeru |title=An Empirical Study of Method Chaining in Java |url=https://doi.org/10.1145/3379597.3387441 |website=Proceedings of the 17th International Conference on Mining Software Repositories (MSR '20) |publisher=Association for Computing Machinery |location=Seoul, Republic of Korea |date=2020 |pages=93–102 |doi=10.1145/3379597.3387441 |isbn=9781450375177 |access-date=2025-09-04

One such example in Java uses the built-in methods of java.util.stream.Stream:

::code[lang=java] import java.util.Arrays; import java.util.List; import java.util.streams.Collectors;

// ...

List numbers = Arrays.asList(10, 25, 30, 45, 60, 75, 90);

List result = numbers.stream() // .stream() returns java.util.stream.Stream .filter(n -> n > 30) .map(n -> n * 2)
.sorted() .collect(Collectors.toList());
::

Note that in Java, filter(), map(), and sorted() return a new shallow copy of the preceding list. However, to operate on the list in-place, the sort() method can be used.

Language Integrated Query (or LINQ) for C# makes extensive usage of method chaining. ::code[lang=csharp] using System; using System.Collections;

// using method chaining: IEnumerble results = SomeCollection .Where(c => c.SomeProperty < 10) .Select(c => new {c.SomeProperty, c.OtherProperty});

results.ForEach(x => { Console.WriteLine(x.ToString()); });

// using LINQ keywords: IEnumerable results = from c in SomeCollection where c.SomeProperty < 10 select new {c.SomeProperty, c.OtherProperty};

foreach (MyObject result in results) { Console.WriteLine(result); } ::

C++20 introduces operator| (the piping operator) and allows LINQ-style chaining operations with the std::ranges namespaces. std::views contains several classes which are invoked through operator(). ::code[lang=c++] import std;

using std::vector; using std::ranges::to; using std::views::filter; using std::views::transform;

vector

// Pipeline: filter even numbers, double them, and then sum the result vector

Design patterns

Main article: Builder pattern, Fluent interface

The Builder pattern relies on constructing an object through method calls rather than immediately in its constructor. For example, java.lang.StringBuilder makes use method chaining to build a StringBuilder. ::code[lang=java] StringBuilder sb = new StringBuilder(); String result = sb.append("Hello, ") .append("world!") .insert(0, "Greeting: ") .replace(10, 18, "beautiful ") .toString(); ::

The Fluent interface pattern relies entirely on method chaining to implement method cascading.

In C++, similar method chaining to Java and C# can be accomplished by having the methods return (for example, for a class StringBuilder, .append() and .replace() could have type StringBuilder& and return *this). However, in C++ it is important to be conscious of potential object slicing if the returned reference is to a parent class, while other languages such as Java, C#, and Rust are not subject to this problem.

References

References

  1. "CMSC 631 – Program Analysis and Understanding".
  2. (4 September 2025). "std::basic_ostream". cppreference.com.
  3. "Stream (Java SE)". docs.oracle.com.
  4. "Language Integrated Query (LINQ) - C# Microsoft Learn". learn.microsoft.com.
  5. "Ranges library (since C++20) - cppreference.com". cppreference.com.
  6. "StringBuilder (Java SE)". docs.oracle.com.
  7. [[Martin Fowler (software engineer). Martin Fowler]], "[http://www.martinfowler.com/bliki/FluentInterface.html FluentInterface]", 20 December 2005
  8. R., Subburaj. (2013). "Object Oriented Programming with C++ ANSI /ISO Standard". Vikas Publishing House.
  9. Grimes, Richard. (2017-04-24). "Beginning C++ Programming". Packt Publishing Ltd.

::callout[type=info title="Wikipedia Source"] This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page. ::

method-(computer-programming)articles-with-example-c++-codearticles-with-example-ruby-codearticles-with-example-java-codearticles-with-example-php-code