Method chaining

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.[1] Local variable declarations are syntactic sugar because of the difficulty humans have with deeply nested method calls.[2][3] 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[4] even though line breaks are often added between methods.

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.

Examples

Scala

A paradigm in functional programming is immutability in method chaining

case class Person(private val name: String = null , private val age: Int = 0 ) {
  def setName(newName: String) = Person( newName, this.age )
  def setAge(newAge: Int) = Person( this.name, newAge )
  def introduce { println( s"Hello, my name is $name and I am $age years old." ) }
}

object App {
  def main(args: Array[String]) {
    // Output: Hello, my name is Peter and I am 21 years old.
    Person().setName("Peter").setAge(21).introduce
  }
}

Java

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();
	}
}

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):

// chaining
$("#person").slideDown('slow')
   .addClass('grouped')
   .css('margin-left', '11px');
// no chaining
var p = $('#person');
p.slideDown('slow');
p.addClass('grouped');
p.css('margin-left', '11px');

C++

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

#include <string>
#include <iostream>
using namespace std;

class Person
{
    string m_name;
    int m_age;

public:
    Person &name(string const &name) {this->m_name = name; return *this;}
    Person &age(int const age) {this->m_age = age; return *this;}

    friend ostream & operator << (ostream &os, Person const &);
};

ostream & operator << (ostream &os, Person const &person)
{
    return os << "Hello, my name is " << person.m_name << " and I am " << person.m_age << " years old.";
}

int main(void)
{
    Person person;
    cout << person.name("Peter").age(21) << endl;

    return 0;
}

ObjectPascal (Dephi)

Method chaining can be expressed in ObjectPascal as follows:

interface
  TPerson = class
    private
        FName: string;
        FAge: Integer;
    public
        function name(const aName: string): TPerson;
        function age(const anAge: Integer): TPerson;
        function introduce(): TPerson;
    end;

implementation

function TPerson.age(const anAge: Integer): TPerson;
begin
    self.FAge := anAge;
    Result := self;
end;



function TPerson.introduce: TPerson;
begin
    ShowMessage(Format('Hello, my name is %s and I am %d years old.', [FName, FAge]));
    Result := self;
end;


function TPerson.name(const aName: string): TPerson;
begin
    self.FName := aName;
    Result := self;
end;


initialization
        TPerson.Create().name('Mohamed').age(49).introduce().Free;

end.

Ruby

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

class Person
  
  def name(value)
    @name = value
    self
  end
  
  def age(value)
    @age = value
    self
  end
  
  def introduce
    puts "Hello, my name is #{@name} and I am #{@age} years old."
  end
  
end

person = Person.new
person.name("Peter").age(21).introduce
# => Hello, my name is Peter and I am 21 years old.

PHP

Implementation and usage of method chaining in PHP:

<?php

class Person {

    protected $name;
    protected $age;

    public function setName($name) {
        $this->name = $name;
        return $this;
    }

    public function setAge($age) {
        $this->age = $age;
        return $this;
    }

    public function __toString() {
        return "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
    }
}

$person = new Person;
echo $person->setName("Peter")->setAge(21); // echo on object automatically calls magic method __toString()

Python

class Person:
    def name(self, value):
        self.name = value
        return self
 
    def age(self, value):
        self.age = value
        return self
 
    def introduce(self):
        print "Hello, my name is", self.name, "and I am", self.age, "years old."
 
person = Person()
person.name("Peter").age(21).introduce()
# => Hello, my name is Peter and I am 21 years old.

Io

Person := Object clone do(
# ::= operator creates a setter which can be used in method chaining
	name ::= "Unknown" 
	age ::= 0
	introduce := method(
		"Hello, my name is #{self name} and I'm #{self age} years old" interpolate println
	)
)

person := Person clone
person setName("Peter") setAge(21) introduce

See also

References

  1. "Applying Method Chaining". http://firstclassthoughts.co.uk/: First Class Thoughts. Retrieved 2011-04-13. In order to simplify repeated object interactions on the same object the old trick Method Chaining originating the world of Smalltalk should be enforced. The idea is to let methods return this rather than void, thus affecting especially set() and add() methods. Method chaining arose during the designers of Smalltalk pursuit to minimize the number of keywords in the language, which lead to the discovery that void is an unnecessary keyword!.
  2. "Session 18 Variable References". Today you learn that variable names are not necessary: they are really syntactic sugar.
  3. "CMSC 631 – Program Analysis and Understanding" (PDF). • Syntactic sugar for local declarations - let x = e1 in e2 is short for (λx.e2) e1
  4. Martin, Robert Cecil (2008). Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall. ISBN 0-13-235088-2.

External links

This article is issued from Wikipedia - version of the 10/12/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.