Method chaining

Method chaining

Method chaining is a common technique for invoking multiple method calls in object-oriented programming languages. Each method returns an object (possibly the current object itself), allowing the calls to be chained together in a single statement.[1] A method chain is also known as a train wreck due to an increasing amount of methods stacked after another in one line.[2]

C#
Object.DoSomething().DoSomethingElse().DoAnotherThing();
PHP
$object->do()->something()->else()

Method chaining is not required. It only potentially improves readability and reduces the amount of source code. It is the core concept behind building a fluent interface.

Contents

Examples

These examples illustrate how method chaining might be implemented and used:

C#

class Person
{
    private string _name;
    private byte _age;
 
    public Person SetName(string name)
    {
        _name = name;
        return this;
    }
 
    public Person SetAge(byte age)
    {
        _age = age;
        return this;
    }
 
    public Person Introduce()
    {
        Console.WriteLine("Hello my name is {0} and I am {1} years old.", _name, _age);
 
        return this;
    }
 
} 
 
//Usage:
static void Main()
{
    Person user = new Person();
    // Output of this sequence will be: Hello my name is Peter and I am 21 years old.
    user.SetName("Peter").SetAge(21).Introduce();
}

C++

class Person
{
        const char* name;
        int age;
 
public:
 
        Person& SetName(const char* name)
        {
                Person::name = name;
                return *this;
        }
 
        Person& SetAge(int age)
        {
                Person::age = age;
                return *this;
        }
 
        void Introduce()
        {
                std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl;
        }
};
 
//Usage:
int main()
{
    Person user;
    // Output of this sequence will be: Hello my name is Peter and I am 21 years old.
    user.SetName("Peter").SetAge(21).Introduce();
}

Java

class Person
{
        private final String name;
        private int age;
 
        public Person setName(final String name) {
                this.name = name;
 
                return this;
        }
 
        public Person setAge(final 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 of this sequence will be: Hello, my name is Peter and I am 21 years old.
                person.setName("Peter").setAge(21).introduce();
        }
}

Actionscript 3

The following is an example of a class with method chaining implemented in Actionscript:

package examples.methodchaining
{
        public class Person
        {
                private var _name:String;
                private var _age:uint;
 
                public function setName(value:String):Person
                {
                        this._name = value;
                        return this;
                }
 
                public function setAge(value:String):Person
                {
                        this._age = value;
                        return this;
                }
 
                public function introduce():void
                {
                        trace("Hello, my name is " + _name + " and I am " + _age + " years old.");
                }
        }
}

Basic usage:

package
{
        import examples.methodchaining
 
        public class Main
        {
                public function Main():void 
                {
                        var person:Person = new Person();
                        // Output of this sequence will be: Hello, my name is Peter and I am 21 years old.
                        person.setName("Peter").setAge(21).introduce();
                }
        }
}

PHP

class Person
{
    private $_name;
    private $_age;
 
    public function setName($name)
    {
        $this->_name = $name;
        return $this;
    }
 
    public function setAge($age)
    {
        $this->_age = $age;
        return $this;
    }
 
    public function introduce()
    {
        printf(
            'Hello my name is %s and I am %d years old.',
            $this->_name,
            $this->_age);
    }
} 
 
$user = new Person();
 
// Output of this sequence will be: Hello my name is Peter and I am 21 years old.
$user->setName('Peter')->setAge(21)->introduce();

See also

References

  1. ^ "Applying Method Chaining". http://firstclassthoughts.co.uk/: First Class Thoughts. http://firstclassthoughts.co.uk/java/method_chaining.html. 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 persuit to minimize the number of keywords in the language, which lead to the discovery that void is an unnecesarry keyword!." 
  2. ^ Martin, Robert Cecil (2008). Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall. ISBN 0-13-235088-2. 

External links


Wikimedia Foundation. 2010.

Игры ⚽ Нужен реферат?

Look at other dictionaries:

  • Chaining — This article is about the teaching procedure. For programming language technique, see method chaining. For information about chaining in expert systems, see Expert system – Chaining. For computer architecture, see Chaining (vector processing).… …   Wikipedia

  • New York City Subway chaining — Chaining numbers can be seen on the pillars in the middle of West Fourth Street – Washington Square. New York City Subway chaining is a method to precisely specify locations along the New York City Subway lines. It measures distances from a fixed …   Wikipedia

  • Backward chaining — (or backward reasoning) is an inference method used in artificial intelligence. It is one of two methods of reasoning that uses inference rules – the other is forward chaining, also known as modus ponens. Backward chaining is implemented in logic …   Wikipedia

  • Forward chaining — is one of the two main methods of reasoning when using inference rules (in artificial intelligence). It is referred in philosophical circle as modus ponens. The opposite of forward chaining is backward chaining. Forward chaining starts with the… …   Wikipedia

  • Exception chaining — Exception chaining, or exception wrapping, is an object oriented programming technique of handling exceptions by re throwing a caught exception after wrapping it inside a new exception. The original exception is saved as a property (such as cause …   Wikipedia

  • Michel Thomas Method — The Michel Thomas Method is an original method developed by Michel Thomas for teaching languages. Thomas stated that his students would be conversationally proficient after a few days study.[1] Thomas has been hired by notable people such as… …   Wikipedia

  • Direct method (education) — The direct method of teaching foreign languages, sometimes called the natural method, refrains from using the learners native language and uses only the target language. It was established in Germany and France around 1900. Characteristic… …   Wikipedia

  • backward chaining method — nenuoseklusis metodas statusas T sritis Kūno kultūra ir sportas apibrėžtis Dalinio mokymo metodo atmaina – sudėtingų technikos veiksmų ir jų derinių mokymas nuo paskutinio judesio ar veiksmo. atitikmenys: angl. backward chaining method vok.… …   Sporto terminų žodynas

  • Rankine's method — is a technique for laying out circular curves by a combination of chaining and angles at circumference, fully exploiting the theodolite and making a substantial improvement in accuracy and productivity over existing methods. Rankine s method is… …   Wikipedia

  • Fluent Interface — Fluent Interfaces[1] stellen in der Software Entwicklung eine Art Programmierschnittstelle dar, die es ermöglicht, beinahe in Satzform Funktionalitäten aufzurufen. Der daraus resultierende Programmcode ist leicht lesbar und macht somit das… …   Deutsch Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”