2

I am wondering when to use mixins? I have read about them. Many authors compare them to interfaces, abstract classes, etc.

Mixins are modules that are mixed-in and modules are a way to group similar methods, constants and classes together.

I have seen examples where a module for math functions is created. It makes sense to group and reuse such functions but should I only mix these in a class if I am faced with an inheritance situation? Should I mix these in anytime I want to use them in a class?

Should they be used exactly like interfaces in other languages or are there other subtleties?

Gilles
  • 2,201
  • 1
  • 19
  • 26

1 Answers1

5

IMHO I'd suggest that they are more like abstract classes in Java than interfaces since they include executable code. Having said that, it is more about reuse through composition than inheritance.

The advantage of a mixins is that they don't require you to inherit. This means that you can include functionality without affecting object hierarchy. It also means that unrelated classes can have common code.

For example using Mongoid doesn't require you to inherit from its class:

class Band
  include Mongoid::Document
end

This makes the class able to be stored and found in MongoDB but you're still able to have your own inheritance.

Perhaps take a read of http://www.rubycentral.com/pickaxe/tut_modules.html and it should become a little clearer.

Dan Murphy
  • 166
  • 2
  • Would you convert very simple classes to mixins, include them and use their methods rather than create instances of these simple classes and call their methods instead? – Gilles Jun 19 '12 at 00:21