Method::Cascade - Use method chaining with any API


    use Method::Cascade;
    use IO::Socket::INET;

      ->setsockopt(SOL_SOCKET, SO_KEEPALIVE, pack("l", 1))
      ->print("GET / HTTP/1.0\r\n\r\n")
      ->recv(my $response, 4096);

    print $response;


Method chaining is a very intuitive and convenient way to make sequential method calls on the same object.

Unfortunately, not all APIs support method chaining. In order for an API to be chainable, every method must return $self. However often there are good reasons for an API to not return $self. For instance, it can be useful for setter methods to return the previous values.

Method cascading is a feature borrowed from Smalltalk. Its advantage is that any API can be used in a chained fashion, even if the designers didn't plan or intend for it to be chainable. You, the user of the API, can choose if you care about the return values and, if not, go ahead and cascade method calls.


This module exports one function: cascade. You should pass it the object that you would like to chain/cascade method calls on. It will return a wrapper object that forwards all method calls to the object you passed in. After forwarding, it returns the same wrapper object.

Because return values are ignored (the methods are in fact called in void context), method cascading is most useful when used with APIs that throw exceptions instead of returning error values. For instance, with DBI, as long as RaiseError is true and AutoCommit is false you can safely do the following:

    cascade($dbh)->do("INSERT INTO admins (name) VALUES (?)", undef, $user)
                 ->do("DELETE FROM users WHERE name=?", undef, $user)


As mentioned, method cascading was first invented in Smalltalk.

Dart is a web-language that has also added this feature. In Dart, the .. operator is a method cascading operator that returns the object the method was invoked on instead of the method call result. Here is a Dart example:

      // and on and on


The Method::Cascade github repo

Method Cascades in Dart

Wikipedia entry on Method Cascading

IO::All - I/O library that makes heavy use of chaining


Doug Hoyte, <>

Thanks to Richard Farr for helping me come up with this idea (during a conversation about C++ smart pointers).


Copyright 2014 Doug Hoyte.

This module is licensed under the same terms as perl itself.