Method cascading

Last updated

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.

Contents

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 used in fluent interfaces, which feature many method calls on a single object.

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. For example, instead of either listing an expression repeatedly:

a.b().c();a.b().d();

or using a temporary variable:

n=a.b();n.c();n.d();

cascading allows the expression to be written once and used repeatedly:

a.b()..c()..d();

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 (receiver, this , self). 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, as in setters). In fluent interfaces this often means that setters return this instead of nothing.

Languages

Pascal

Within the component statement of the with statement, the components (fields) of the record variable specified by the with clause can be denoted by their field identifier only, i.e. without preceding them with the denotation of the entire record variable. The with clause effectively opens the scope containing the field identifiers of the specified record variable, so that the field identifiers may occur as variable identifiers.

withdatedoifmonth=12thenbeginmonth:=1;year:=year+1endelsemonth:=month+1{ is equivalent to }ifdate.month=12thenbegindate.month:=1;date.year:=date.year+1endelsedate.month:=date.month+1

Smalltalk

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: [1]

selflistPaneparentcolor:Colorblack;height:17;width:11

Compare with separate statements, terminated with a period, also using a variable for abbreviation:

|parent|parent:=selflistPaneparent.parentcolor:Colorblack.parentheight:17.parentwidth:11.

One subtlety is that the value of a method call ("message") in a cascade is still the ordinary value of the message, not the receiver. This is a problem when you do want the value of the receiver, for example when building up a complex value. This can be worked around by using the special yourself method that simply returns the receiver: [2]

Object>>yourself^self

For example, the "add an object to a collection" method (Collection>>add: anObject) returns the object that was added, not the collection. Thus to use this in a cascade in an assignment statement, the cascade must end with yourself, otherwise the value will just be the last element added, not the collection itself:

all:=OrderedCollectionnewadd:5;add:7;yourself.

Visual Basic

Visual Basic uses the With statement to enable an arbitrary number of method calls or property accesses on the same object:

WithExpressionThatReturnsAnObject.SomeFunction(42).Property=valueEndWith

With..End With blocks in Visual Basic can be nested:

WithExpressionThatReturnsAnObject.SomeFunction(42).Property=valueWith.SubObject.SubProperty=otherValue.AnotherMethod(42)EndWithEndWith

Dart

Among newer languages, Dart implements cascades, using a double-dot .. "cascaded method invocation operation". Unlike Smalltalk, in Dart the value of a cascaded method invocation is the receiver (base object), not the value of the (uncascaded) method invocation, and thus there is no need for yourself. Dart uses properties, and thus rather than using method syntax for getters and setters (foo.getBar(); foo.setBar(b);), it uses field value/assignment syntax (foo.bar; foo.bar = b;), and cascades work with assignments:

a..string='Hello world!'..done=true;

is equivalent to:

a.string='Hello world!';a.done=true;

Related Research Articles

Smalltalk Object-oriented programming language first released in 1972

Smalltalk is an object-oriented, dynamically typed reflective programming language. Smalltalk was created as the language underpinning the "new world" of computing exemplified by "human–computer symbiosis". It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Diana Merry, Scott Wallace, and others during the 1970s.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

Conditional (computer programming) Programming language construct that performs actions according to boolean conditions

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition.

In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses. Among those that do, the extent to which metaclasses can override any given aspect of class behavior varies. Metaclasses can be implemented by having classes be first-class citizens, in which case a metaclass is simply an object that constructs classes. Each language has its own metaobject protocol, a set of rules that govern how objects, classes, and metaclasses interact.

In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c".

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

Java syntax Set of rules defining correctly structured programs

The syntax of Java refers to the set of rules defining how a Java program is written and interpreted.

The uniform access principle of computer programming was put forth by Bertrand Meyer. It states "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation". This principle applies generally to the syntax of object-oriented programming languages. In simpler form, it states that there should be no syntactical difference between working with an attribute, pre-computed property, or method/query of an object.

C Sharp (programming language) Multi-paradigm (object-oriented) programming language

C# is a general-purpose, multi-paradigm programming language. C# encompasses static typing, strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines.

Magik is an object-oriented programming language that supports multiple inheritance and polymorphism, and it is dynamically typed. It was designed and implemented in 1989 by Arthur Chance of Smallworld Systems Ltd. as part of Smallworld Geographical Information System (GIS). Following Smallworld's acquisition in 2000, Magik is now provided by GE Energy, still as part of its Smallworld technology platform.

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field and a method or a property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to 'getter' and 'setter' method calls. The field-like syntax is easier to read and write than many method calls, yet the interposition of method calls "under the hood" allows for data validation, active updating, or implementation of what may be called "read-only fields".

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

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.

C# 4.0 is a version of the C# programming language that was released on April 11, 2010. Microsoft released the 4.0 runtime and development environment Visual Studio 2010. The major focus of C# 4.0 is interoperability with partially or fully dynamically typed languages and frameworks, such as the Dynamic Language Runtime and COM.

Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Objective-C was the standard programming language supported by Apple for developing macOS and iOS applications using their respective application programming interfaces (APIs), Cocoa and Cocoa Touch, until the introduction of Swift in 2014.

In object-oriented programming, the safe navigation operator is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument.

In object-oriented programming, forwarding means that using a member of an object results in actually using the corresponding member of a different object: the use is forwarded to another object. Forwarding is used in a number of design patterns, where some members are forwarded to another object, while others are handled by the directly used object. The forwarding object is frequently called a wrapper object, and explicit forwarding members are called wrapper functions.

References

  1. Beck 1997, "Cascade", pp. 183–185.
  2. Beck 1997, "Yourself", pp. 186–188.
Dart