The composition and inheritance in Ruby class
In the previous blog I showed how to use undefined methods in class by attr_accessor and method_missing. Let's talk more about how to use undefined methods by inheritance and composition since it's useful for the object-oriented programming. Here we define super powers of the Incredibles.
However, with great power there must also come great responsibility. Let's define their busy life here, and supermen get super power by the inheritance. Notice the "< Supermen" below:
See, there's no method definition of super powers, but we can still use it because the inheritance in Ruby class. That's convenient!. But wait, they also got an intensive baby sitting schedule mentioned in my previous blog too:
What a busy schedule of the baby sitting! Don't you want to list all their shifts? Let's try it with each method. But wait, we didn't define the
each method so Ruby will reject our request of using
baby.each. Is there a way to list all of their shifts? It would be so nice if we can use all Enumerable methods here. In Carlson & Richardson's Ruby Cookbook Chapter 9.4, they showed a pretty mixin by adding the "include" and defining "each" to use all 22 Enumerable methods in one shot.
Now we can marvellously use all core methods defined in the Enumerable module! Because there's no multiple inheritance in Ruby, in one customized class we can use methods from many other classes by mixin. Isn't that great?
By the inheritance the class got all methods defined in the father class, for example, Incredibles ARE supermen. By mixin we got specific methods from other class, and that's the idea of the composition, say, Incredibles schedules' HAVE Enumerable methods. There are many people hotly debating either inheritance or composition is better. In my point of view, as long as the handling of the repetitive codes is elegant, highly readable and maintainable, either or both ways can be applied in certain conditions.