DEV Community

Kelly Stannard
Kelly Stannard

Posted on

Mixins are inheritance

Inheritance is getting a bad rap and rightfully so in my opinion. Inheritance has turned out to be a specialist tool for specific situations and was unfortunately overused. Long story short, try composition before inheritance.

Now, that said, I have come across developers who understand the above and yet still fall unwittingly into the trap of inheritance over-use. This happens because they think mixins are composition, but mixins are actually Ruby's answer to multiple inheritance. Don't believe me?

Here is an example of classic inheritance:

class Superclass; def talk; "world"; end; end
class Subclass < Superclass; def talk; "hello #{super}"; end; end
Enter fullscreen mode Exit fullscreen mode

Now here is an example usage and a look under the hood.

puts Subclass.new.talk
#> hello world
puts Subclass.ancestors.inspect
#> [Subclass, Superclass, Object, PP::ObjectMixin, Kernel, BasicObject]
Enter fullscreen mode Exit fullscreen mode

Now, here is the same code using mixins. Note that the method signature is identical.

module Superclass; def talk; "world"; end; end
class Subclass; include Superclass; def talk; "hello #{super}"; end
Enter fullscreen mode Exit fullscreen mode

And again, a usage and a look under the hood. Note that they are identical to the classic inheritance implementation.

puts Subclass.new.talk
#> hello world
puts Subclass.ancestors.inspect
#> [Subclass, Superclass, Object, PP::ObjectMixin, Kernel, BasicObject]
Enter fullscreen mode Exit fullscreen mode

To sum up, mixins are going to run into most of the problems you would get with inheritance because they are a type of inheritance.

Oldest comments (0)