Newbie question: function overloading

From: Dimitrios Galanakis [mailto:galanaki@uiuc.edu]

I need to define a method that performs differently when
operated on objects of different type (overloading).
Currently I use various if’s to check for the type of
the object as follows:

def somefunction(a)
if a.kind_of?(someType)
expression1
return
end
if a.kind_of(someOtherType)
expression2
return
end
end

I would do it like this …

class SomeType
def somefunction
expression1
end
end

class SomeOtherType
def somefunction
expression2
end
end

Then just call:

a.somefunction

If you still feel the need to pass obj as an argument to somefunction, you
can always use:

def somefunction(a)
a.somefunction
end

···


– Jim Weirich / Compuware
– FWP Capture Services
– Phone: 859-386-8855

I would do it like this …

···

On Fri, 3 Oct 2003, Weirich, James wrote:

class SomeType

def somefunction

expression1

end

end

class SomeOtherType

def somefunction

expression2

end

end

Then just call:

a.somefunction

If you still feel the need to pass obj as an argument to somefunction, you

can always use:

def somefunction(a)

a.somefunction

end

And if you’d like to see that diagrammed:
http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html

:slight_smile:

And in our particular instance, we have an even stronger reason to move
to polymorphism because the condition was based on a type (rather than
an enumeration in the diagram example).

···

On Thu, 2003-10-02 at 17:12, Chad Fowler wrote:

And if you’d like to see that diagrammed:
Replace Conditional with Polymorphism


– Jim Weirich jweirich@one.net http://onestepback.org

“Beware of bugs in the above code; I have only proved it correct,
not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)