Inheritance vs Composition

Okay, so in my studying yesterday I went over the concept of Inheritance and how it applies to classes. Today I’m going over composition, which is an alternative to inheritance and is another way to create relationships between objects and combine simple objects into more complex ones. Inheritance and Composition are called design patterns and they can be used as templates for your code.

With inheritance, we think of one class as the parent and another class as the child. The child has all of the attributes and methods that the parent has, but sometimes the child is different from the parent so we can use the super class to override an inherited method.

With composition, it’s more like one class is a car and another is a steering wheel or an engine. The car is a complex object and it is made up of objects of a similar type. With composition, you build up the functionality of a class through other classes.

vroom vroom!

vroom vroom!

Another important design pattern is the Factory. A Factory is pattern that manufactures other objects. This pattern is modeled as a Factory class, module or method. Factory methods can create objects without specifying which class the object will belong to. They let the class who implement the factory method decide which object belongs to which class. Factory methods rely on inheritance.

Screen Shot 2014-02-09 at 2.49.31 PM

Click to visit the Ruby Forum page on The Factory Method

So when do you use composition and when do you use inheritance?

Use composition to package up code into modules that is used in many different unrelated places and situations. If you are unsure, default to using composition.

Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept, or if you have to because of something you’re using.

So here’s my problem, I understand all of the above, but I’m still not 100% sure how to connect my factory method to the rest of my code so that it works. I understand the include method, but I’m still confused. I think that will be something that I need to talk to a DBC coach or teacher about. Look for edits once I figure it out!

Helpful Links:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s