In other languages we have interfaces:
different methods can be called with different count of args , or type of
args.
In Ruby we can simulate this using one method and case.
But it must be in the original method (changing the case statement), so
are there more "OO"-like ways?
(Adding a new method for a new type later, not (much) touching the
original method)
To sum it up: you are talking about method overloading here.
I'd say Ruby's is the *more* OO way (there is one way to send a particular
message to a particular object; if you need to send a different message, it
should be a different method.)
I agree.
And if you're worried about the 'types' of the arguments, don't. "Type" is a
Bad Word™ in Ruby. We use duck typing, which is to say: if a method's
contract says it requires certain functions/methods/properties of
parameters, it doesn't matter what class a given parameter object has, as
long as it has the right methods defined.
I'm not sure what your final parenthetical means, but yeah that's what I'd
suggest. For example:
* If the method has an optional parameter, make it optional (with a default
value).
* If it behaves differently when it has two args instead of one, then those
are two different methods.
* If it behaves differently when passed something number-like instead of
something string-like, then those are two different methods.
Of course that's a very strong statement; there's no law against having a
case statement in your function to switch between different code paths based
on the interface (or class) of parameters.
It is also more efficient to not use case but use proper method
dispatch to select one of the appropriate methods. Plus, code will
become less complex.
Btw. if the topic is multiple dispatch, then there are other
techniques that can be used, e.g. a Hash with lambdas:
class X
DISPATCH = {
String => lambda {|this, s| puts s},
Fixnum => lambda {|this, n| puts n.to_s}, # silly example
}
def m(arg)
DISPATCH[arg.class][self, arg]
end
end
It's not nice though.
Kind regards
robert
···
On Mon, Jan 23, 2017 at 12:49 PM, Matthew Kerwin <matthew@kerwin.net.au> wrote:
On 23 January 2017 at 21:29, Die Optimisten <inform@die-optimisten.net> > wrote:
--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/