Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
    
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 0:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.