Tuesday, March 12, 2013

Composite classes and multi-table inheritance

I'm working on a project where I have a set of classes that have (a) common data and behavior and (b) distinct data and behavior. At first glance, it would seem that inheritance is the thing to do here. But, for a number of reasons (Google "composition over inheritance"), I preferred to go down the composition route.

I Googled "Multi Table Inheritance" (MTI) since this seemed to be the key phrase for getting composition to work and found a couple of really helpful posts. In particular, Multiple Table Inheritance with ActiveRecord was a real gem!In fact, just about all the code in these post either came directly from this post or was directly inspired by it.


They were a bit terse, and I thought it might be helpful to provide a longer, blow-by-blow account of how I got my composition and MTI working.

In this example, I have two classes that I want to have shared data structures and behavior. They are: Event and Trip. To accomplish this, I am going to create a third class, called EventBase, that will contain the shared data structures and behavior. I will then include EventBase (by way of composition) in each of Event and Trip so that they can have the desired data structures and behaviors.

Next Post: Create EventBase


References:

Multiple Table Inheritance with ActiveRecord
Multiple Table Inheritance in Rails 3

No comments:

Post a Comment