what is the difference between cascading and chaining

Viewed 1720

I just find from a forum about cascade. The question was what does cascading means in poo. I tried to find to google the answer, also tried to find some other stackoverflow threads about if but I couldn't. I just find this link http://en.wikipedia.org/wiki/Method_cascading

I know what is chaining, I used it, most in javascript, jquery and other languages, but I coundn't understand the difference between chaining and cascading. Can anybody help me? Or can anybody provide some useful links regarding to this?

2 Answers

Chaining is where you return the result of the method call to be used in the next call.

c#

Enumerable.Range(0,10).Skip(1).Aggregate(myList.First(),(result,listItem) => result += listItem));
//results in 45 being returned

Cascading can be implemented by using chaining when this is returned (making it sometimes tricky to differentiate between the two). jQuery does this.

jquery

$("#myId").css("background-color","blue").fadeIn().fadeOut();
//results in $("#myId") being returned

The definition is pretty clear on the Wikipedia page you linked:

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.

This means that, a.b() returns a mutated a instance with method cascading. a.b() returns something different from b() with method chaining.

So, this is method cascading:

class YourClass {
    public YourClass b() {
        // do stuff
        return this;
    }

    public YourClass c() {
        // do stuff
        return this;
    }
}

..which allows: yourClass.b().c();.

..and this is method chaining:

class YourClass {
    public SomeOtherObject b() {
        // do stuff
        return new SomeOtherObject(this);
    }
}

class SomeOtherObject {
    private YourClass _owner;

    public SomeOtherObject(YourClass owner) {
        _owner = owner;
    }

    public void c_onOtherObject() {
    }
}

..which allows: yourClass.b().c_onOtherObject();.

EDIT: I rolled back my previous edit. It appears the above is correct and the terms aren't flipped incorrectly.

Related