Alex Rivera | Logout

ruby inheritance vs mixins

Asked 2009-08-15T21:14:39.603
137

In Ruby, since you can include multiple mixins but only extend one class, it seems like mixins would be preferred over inheritance.

My question: if you're writing code which must be extended/included to be useful, why would you ever make it a class? Or put another way, why wouldn't you always make it a module?

I can only think of one reason why you'd want a class, and that is if you need to instantiate the class. In the case of ActiveRecord::Base, however, you never instantiate it directly. So shouldn't it have been a module instead?

Edit
Report

2 Answers

42

I think mixins are a great idea, but there's another problem here that nobody has mentioned: namespace collisions. Consider:

module A
  HELLO = "hi"
  def sayhi
    puts HELLO
  end
end

module B
  HELLO = "you stink"
  def sayhi
    puts HELLO
  end
end

class C
  include A
  include B
end

c = C.new
c.sayhi

Which one wins? In Ruby, it turns out the be the latter, module B, because you included it after module A. Now, it's easy to avoid this problem: make sure all of module A and module B's constants and methods are in unlikely namespaces. The problem is that the compiler doesn't warn you at all when collisions happen.

I argue that this behavior does not scale to large teams of programmers-- you shouldn't assume that the person implementing class C knows about every name in scope. Ruby will even let you override a constant or method of a different type. I'm not sure that could ever be considered correct behavior.

answered 2012-04-26T23:59:32.560
-1

Right now, I'm thinking about the template design pattern. It just wouldn't feel right with a module.

answered 2009-08-15T21:27:24.570

Your Answer