djberg96 ([info]djberg96) wrote,
@ 2006-03-27 07:46:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
Current mood:geeky
Entry tags:ruby

Keep your classes subclassable!
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.



Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…