Learn Ruby the Hard Way – Exercise 44 Inheritance VS Composition

Here is my work for Exercise 44.

My Exercise 44 code:  using inheritance, using composition, and using a mixin.
There is only one study drill for this exercise, and that is to read this Ruby style guide.

Wow, the style guide definitely introduces a lot of things to keep in mind.

I learned about the three different ways subclasses can inherit super-classes’ methods. First, a method can be implicitly inherited from the parent class. Second, a method can be ‘overwritten’ in the child class. Defining the method again in the child class will override the parent method of the same name. And lastly, a defined child method can alter the parent method through the super function call (calls the method of the same name in the parent class).

This exercise showed three different ways to achieve the same goals:
1) You can write parent and child classes, with the child is-a parent relationship. This would be using Ruby inheritance.
2) You can use composition. You can create an instance of another Other class in the initialize function. This makes the method’s in the Other class ‘available’ to use in your class. This is composition, where one class is composed of other classes as parts.
3) You can use a mixin. You create a module with code that you will repeatedly use in classes. Then in the class, you include the module as a mixin. This was only lightly touched upon in this exercise.

P.s Adding this after reading 10 Interview Questions Every JavaScript Developer should know: Favor composition over class inheritance (Zed Shaw also echoes this sentiment in his book). Why? Because with class inheritance things can get REALLY messy –> All you wanted was a banana, but you got a banana being held by a gorilla in a jungle.


Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s