World Library  
Flag as Inappropriate
Email this Article

Method chaining

Article Id: WHEBN0017218690
Reproduction Date:

Title: Method chaining  
Author: World Heritage Encyclopedia
Language: English
Subject: Method cascading, JFugue, Anaphoric macro, Method (computer programming), Smalltalk
Collection:
Publisher: World Heritage Encyclopedia
Publication
Date:
 

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, and requires that the return value be mutable (e.g., the original object, not a copy).

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 
#include 
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;
}

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:

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. ^
  2. ^
  3. ^
  4. ^

External links

  • Creating DSLs in Java using method chaining concept
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and USA.gov, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for USA.gov and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
 
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
 
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.
 



Copyright © World Library Foundation. All rights reserved. eBooks from Hawaii eBook Library are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.