Jared
Jared

Reputation: 661

Ruby on Rails Best Design Pattern Instead of Single Table Inheritance?

I'm a junior developer working on a new Rails App and need some assistance in deciding which design pattern is best to use to model different types of orders. I was planning on utilizing the Single Table Inheritance pattern for these problems, but have heard several developers say I should stay away from this pattern. Any ideas are appreciated!

Orders need different types. Each type shares some database columns, however will also need some columns which are not shared by the other types (as we further develop the business and begin to handle new types of orders). I want to avoid duplicating columns in different database tables, and I also want to avoid having one table for everything as each type will not need everything from a single table.

Orders can be created by either customers or retailers on behalf of one of their customers. Another type of Order is the WelcomeKit which we send to customers directly before they send in their order

All Orders need the following:

All RepairOrders also need the following:

All RetailOrders need everything from Orders and RepairOrders and also:

All WelcomeKits only need information from the Order table.

Is Single Table Inheritance the best way to handle this? Are there any other patterns that are better suited for long term maintainability? Any specific help on both database and model design would be awesome! Thanks.

Upvotes: 2

Views: 817

Answers (1)

The Whiz of Oz
The Whiz of Oz

Reputation: 7043

I highly recommend you to read the book by Sandi Metz, Practical Object-Oriented Design in Ruby, as it touches upon this very subject in great detail. Since I don't have it with me right now, I will copy a short paragraph written by Ben Johnson that kind of summarizes the overall strategy:

Always prefer composition to inheritance (classes) unless you can defend inheritance. Also, consider if you have one basic thing with subtypes or something that is made up of parts.

If X is-a Y → Inheritance (class)

If X has-a Y → Composition

IF X behaves-like-a Y → Duck type (module)

Good design naturally progresses towards small, independent objects that rely on abstractions.

I think that in your particular situation inheritance may be a good fit.

Upvotes: 3

Related Questions