Method cascading
In object-oriented programming, method cascading is syntax which allows multiple methods to be called on the same object. This is particularly applied in fluent interfaces.
For example in Dart, the cascade:
a..b()
..c();
is equivalent to the individual calls:
a.b();
a.c();
Method cascading is much less common than method chaining – it is found only in a handful of object-oriented languages, while chaining is very common. A form of cascading can be implemented using chaining, but this restricts the interface; see comparison with method chaining, below.
Application
Cascading is syntactic sugar that eliminates the need to list the object repeatedly. This is particularly useful if the object is the value of a lengthy expression, as it eliminates the need to either list the expression repeatedly or use a temporary variable.
This is particularly used in fluent interfaces, which feature many method calls on a single object.
Comparison with method chaining
Given a method call a.b()
, after executing the call, method cascading evaluates this expression to the left object a
(with its new value, if mutated), while method chaining evaluates this expression to the right object.
- Chaining
The following chain (in C++):
a.b().c();
is equivalent to the simple form:
b = a.b();
b.c();
- Cascading
The following cascade (in Dart):
a..b()
..c();
is equivalent to the simple form:
a.b();
a.c();
Cascading can be implemented in terms of chaining by having the methods return the target object (this). However, this requires that the method be implemented this way already – or the original object be wrapped in another object that does this – and that the method not return some other, potentially useful value (or nothing if that would be more appropriate). In fluent interfaces this often means that setters return this instead of nothing.
Another benefit of cascading is that it can also be applied to assignments. The following cascade (Dart):
a..string = 'Hello world!'
..done = true;
is equivalent to:
a.string = 'Hello world!';
a.done = true;
Languages
Method chains and cascades were both introduced in Smalltalk; most subsequent object-oriented languages have implemented chains, but few have implemented cascades. In Smalltalk the semicolon operator can be used to send different messages to the same object.
Among newer languages, Dart implements cascades.
Related techniques
A similar technique is for a (left-associative) binary operation of two objects to return the left object as its value, allowing cascading in the same way. A common example is iostream in C++, where for example <<
returns the left object, allowing cascading.
Compare:
a << b << c;
equivalent to:
a << b;
a << c;
with:
a..send(b)
..send(c);
equivalent to:
a.send(b);
a.send(c);
External links
- Dart
- "Method Cascades in Dart", Gilad Bracha, February 17, 2012
- Milestone 1 Language Changes, "Cascades", Bob Nystrom, July 2012 (updated March 2013)