The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Keep your classes subclassable!

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
Keep your classes subclassable! Posted: Mar 27, 2006 7:26 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Daniel Berger.
Original Post: Keep your classes subclassable!
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
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.

Read: Keep your classes subclassable!

Topic: Ruby Classes as Directories, Methods as Files Previous Topic   Next Topic Topic: making functional test failures readable

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use