Creating a "fluent" interface

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 = ....., comp)
     @components << comp

   when Number

   return self

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

I just came across an article : in which the author
creates this interface:

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

It seems that with() returns the order object, however in HPK, he is
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.


Posted via