in reply to
Re: chaining method calls
in thread chaining method calls
I like it. It feels very Smalltalky. You're sending a bunch of messages to the object, so why repeat the invocant? Expressions have results, so why not use them?
In Smalltalk this is called a "cascade", and there's special syntax to support it. In Smalltalk, if you send two messages to the object anObject (i.e., if you invoke two of anObjects's methods), you can use cascading to rewrite
anObject foo; bar.
Both messages get sent to anObject
, regardless of what the first method returns. That is, the return value from foo
is ignored. The value of this expression is whatever is returned from bar.
Perl has no notion of method call cascading, so to simulate cascading, all member functions in a simulated cascade chain (except that final one) need to return self. This works great if you're making a chain of calls for side-effects, and less great if you're composing an expression from a set of cascaded calls, and are interested in the final value, because of the requirement that all cascadable methods return self.
My opinion is that cascading is an idiom that doesn't translate well into Perl. Without a special syntax to designate a cascade, a simulated cascade is indistinguishable from a gross violation of the Law of Demeter.