From: Gavin Sinclair Date: 2002-11-22T01:21:12+09:00 Subject: Re: [FAQ] Multiple constructors? From: "Nat Pryce" > On Thu, 2002-11-21 at 15:27, Gavin Sinclair wrote: > > If you need to branch on type, you can do this > > > > def initialize(value) > > case value > > when String then ... > > when Regexp then ... > > else ... > > end > > I would avoid this because it is not branching on type, but instead > branching on how an object *implements* its type, which should be of no > concern to other objects. For example, this code would break if I passed > it an object that acted exactly like a Regexp but was not an instance of > the Regexp class. That object would have the same *type* as objects of > class Regexp, but would have a different *implementation*. See > http://www.rubygarden.org/ruby?TypesInRuby for a more detailed > explanation. That's fair enough - like I say, none of these approaches is a perfect fit - but sometimes you can be pretty sure what you're dealing with. It sort of depends how far and wide your code is going to spread. For better or worse, code like that above is seen in widely used libraries. Even though most experienced rubyists would agree that it's to be avoided, sometimes it makes the most sense. > If you want to have different constructors for different argument types, > define different constructors on your class. Your code will then be > both more flexible and more readable. E.g. If you had a class that > could be created with either a String and a Regexp you would define > constructors new_from_string(a_string) and new_from_regexp(a_regexp). I have an aesthetic problem with that, but again, sometimes it's the most desirable solution. At the end of the day, if I find myself *really needing* Java-style overloaded methods, I question my design. > Cheers, > Nat.