Sep 18, 2008 10
Using Single Table Inheritance Is Okay
This week I noticed an excellent article by Matt Moore where he assembled a check list of code quality items that each developer in his teams should sign off on for each of their projects. While I agree with most of Matt’s check list as a whole, I don’t agree with his argument that the Single Table Inheritance (STI) feature in the Rails framework shouldn’t be used.
In a project that I am currently working on I am using the STI feature to allow a common set of objects to share similar properties but are of different types. For example, I have a table of factors but each factor can either be a benefit or a risk. Each factor has 2 fields at the moment: name and weight. Using the STI feature I can create a single database table called factors that allows me to store benefits and risks in them.
Making Design Decisions
This is fine for a simple example, but what if one of my types needs an extra field or more? This is where things can get messy. At this point the team faces a design decision. Does the team just add the fields to the STI table or do we re-factor out the types into their own tables?
In most cases you’ll want to re-factor out the types into their own tables. For those other cases where you’ll just add the field to the STI table. This is fine for one field, but if your adding more I would suggest you re-factor the STI table into seperate tables for each type.
If you have set-up your models correctly and you have a set of unit tests to back them up, then you should have no problems breaking this STI table into two tables. By using unit tests to ensure your code changes are correct and migrations to make the required changes to your database, you’ll have your STI table re-factored into two or more single tables.
Know The Framework
The Rails framework is a complex thing if your learning, but like most things if you practice and learn what’s involved in its features, you’ll make good design decisions that don’t hamper the progress of your project. In this case, by learning the correct use of the STI feature and where it can be applied can save hours of bedlam later.
If you want to find out more about the STI feature in the Rails framework, I recommend first familiarising yourself using Martin Fowler’s Single Table Inheritance description and then checking out the Rails documentation for ActiveRecord.
Recent Comments