views:

18

answers:

0

I've faced this issue several times. I have a method that adds a component to a container. Should it return self (this) (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).

In a Tree class, if i wish to add a heirarchy such as "/Users/jane/projects/ruby", to do: tree << "Users" << "jane" << "projcets" is easy if component is returned, but difficult if "self" is returned.