Search code examples
rubyinterfacepolymorphismduck-typing

Is this use of polymorphism misleading and therefore bad design?


If I have the following ruby module which implements a particular interface (apply in this case)

module FooApplier
  def apply
    foo
  end
end

...and all other "Appliers" are classes, not modules, is it misleading to other engineers to pass FooApplier to receivers which expect the applyinterface?

Let's assume the application using FooApplier runs perfectly fine, but let's also assume that some other engineer didn't take the time to pour over every last byte of my code. If they decide to send something like .new to the FooApplier which somehow induces some subtle bug, is the onus on my design, or the engineer for making assumptions and neglecting to read my code?


Solution

  • The way your module is presented here, it won't work as a stand-in for a class. Let's look at a class first:

    class BarApplier
      def apply
        bar
      end
    end
    

    apply here is an instance method, so callable on instances of BarApplier, i.e. BarApplier.new.apply. This will not be possible for your module.

    Unless of course apply was meant to be a class or module method, in which case your question was misleading since it then should be def self.apply.

    But to answer the more general question, in a duck-typed language the sent messages are the interface. In my opinion the caller should make no assumptions about other methods being present. In your specific case, if apply is the only method in the "contract", assuming that the same entity also responds to new is invalid in my opinion.