Method cascading

I finally have a tool from fluent interfaces toolbox I needed. Usually you have some type of container with a method:

def !add(elem T) Void
  %% adding element
end

Wait, or should be it like this:

def !add(elem T) 'Self
  %% adding element
  return this;
end

The second form allows method chaining, but on the other hand there is overhead of result passing no matter if anyone uses it or not. And what about returning boolean flag indicating whether adding was successful or not. In such case we couldn’t return the container.

Method cascading answers some of those questions, we don’t need a version which cooperates with us because we isolate the object and reuse it:

coll |> !add(a) |> !add(b);

b is not added to the outcome of adding a (it would be a method chaining), but to the isolated object on the left — coll. Of course sometimes method cascading can have the same effect as method chaining, but in general they are two distinct tools.

The above code is equivalent to:

coll!add(a);
coll!add(b);

You can find more about method cascading at Wikipedia.

I took the symbols of the pipe operator — but not the meaning — from Elm (if I remember correctly I first saw it in Seven More Languages in Seven Weeks by Bruce Tate et al) and initially I thought it was function cascading operator which is not.

Advertisement
Tagged ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: