Creating a "fluent" interface

R

Rahul Kumar

I've faced this issue several times. I have a method that adds a
component to a container. Should it return self (for method chaining),
or the component.

The problem arises when the method 'add' might create the component (for
user's convenience). The caller now needs the handle of the component to
call methods on it. I obviously cannot have different return values in
different classes in my library. Is there any way to have both !

here's a dummy sample:

def add comp
case comp
when Component
# just add it, or assign it
@components << comp
when String
# convenience method .. complicated creation of component
comp = Component.new( ....., comp)
@components << comp

when Number
...
end

return self
end

In cases, where the user sends a string, i create a component object but
caller
will have to be provided other ways of retrieving component.

I just came across an article :
http://martinfowler.com/bliki/FluentInterface.html in which the author
creates this interface:

private void makeFluent(Customer customer) {
customer.newOrder()
.with(6, "TAL")
.with(5, "HPK").skippable()
.with(3, "LGV")
.priorityRush();
}

It seems that with() returns the order object, however in HPK, he is
able
to call skippable() on the line item. Since the example given is Java, I
don't think that there's a "method_missing" available that can forward a
call from component to self. Anyway, the same method "add" can exist in
both container and component (as in the case of a Tree object).

Look forward to your thoughts. rk.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top