?

Log in

No account? Create an account
Keep your classes subclassable! - Testing 1,2,3... [entries|archive|friends|userinfo]
djberg96

[ website | Netrunner Tracker ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Links
[Links:| Ruby Home RubyForge RAA comp.lang.ruby Ruby Documentation ]

Keep your classes subclassable! [Mar. 27th, 2006|07:46 am]
djberg96
[Tags|]
[mood |geeky]

Evan Phoenix submitted a patch to ruby-core recently that caused me have one of those "duh!" moments, accompanied by a smack to the forehead. What am I talking about? I'm talking about not hard coding your class names, thus making your classes difficult or impossible to subclass.

Consider this example:
class Foo
   def create_new
      Foo.new
   end
end

Zip it and ship it, right? Except, a short time later, someone uses your code and decides they want to subclass Foo:
class Bar < Foo
end

Bar.new.create_new # Oops!

See the problem? They're going to get back a Foo class instead of a Bar class because you hard coded the class name in the method.

The solution is to keep your classes dynamic:
class Foo
   def create_new
      self.class.new
   end
end

Bingo, baby.
linkReply