Monday, November 27, 2006

Put Away that Hammer: Use Ruby-fu to avoid unnecessary inheritance in Rails

Overusing inheritance is a well-known pitfall of object oriented languages. Ruby provides insanely great toys to allow you to extend classes (or even objects) without resorting to ugly inheritance hierarchies that are not relevant to your real-world domain model.

While working on Rails projects I have learned to break old habits:
  • Don't inherit from a class simply to extend it.
  • Don't write a wrapper class to extend an existing class.
Instead, do the following:
  • Extend a project class using "include" to include a module.
  • Extend Ruby's classes (careful!) the same way.
  • Or - extend an existing class by declaring it and adding additional methods.
  • In some scenarios, extend an object rather than a class.
Extremely useful articles in greater depth are at Luke Redpath and in Code Snippets. Ruby modules are documented in the Ruby Core API.

No comments: