tags:

views:

460

answers:

4

what is the difference between mix-in and inheritance

+3  A: 

mix-in is a specific, restricted case of (multiple) inheritance used for implementation purposes; some languages (e.g. Ruby) support it without supporting generalized multiple inheritance.

Alex Martelli
+4  A: 

A Mix in is typically used with multiple inheritance. So, in that sense, there's "no difference".

The detail is that a Mix in is rarely useful as a standalone object.

For example, say you have a Mix In name "ColorAndDimension", which adds a color property and width and height.

Now, you could add ColorAndDimension to a, say, Shape Class, a Sprite Class, a Car Class, etc. And they will all have the same interface (say get/setColor, get/setHeight/Width, etc.)

So, in the generic case a Mix in IS inheritance. But you can argue it's a matter of the role of the class in the overall domain as to whether a Mix in is a "primary" class or simply a mix in.

Edit -- just to clarify.

Yes, a Mix In can be considered, in todays modern lingo, an Interface with an associated Implementation. It really is just plain, old, everyday multiple inheritance using a plain, old, everyday class. It just happens to be a specific application of MI. Most languages don't give a Mix In any special status, it's just a class that was designed to be "mixed in", rather than used stand alone.

Will Hartung
what is the diff between a mixin and an abstract class?
Johnd
abstract classes can be sub-classed, mixins cannot.
Bayard Randel
Usually a mixin will provide implementation, while an abstract class doesn't. There are no inheritance restriction on mixins, although I don't think I've ever seen one sub-classed.
David Thornley
+3  A: 
Bayard Randel
What does this have to do with mixins?
David Thornley
It's demonstrating how mixins exist outside the inheritance hierarchy.
Bayard Randel
+1: The image is 404 now, but the article cleared up the concept a bit.
Rekin
+1  A: 

"A mixin is a fragment of a class in the sense that it is intended to be composed with other classes or mixins." -DDJ

A mixin is a class or code fragment which is not intended for stand-alone use, but instead you're supposed to use it inside of another class. Either composing it as a member field/variable or as a code segment. I have the most exposure to the later. It's a little better than copy-pasting boilerplate code.

Here's a great DDJ article that introduces the subject.

The Half-Life 2 / "Source" SDK is a great example of C++ mixins. In that environment macros define sizable blocks of code which can be added to give the class a specific "flavor" or feature.

Look at the Source wiki example: Authoring a Logical Entity. In the example code the DECLARE_CLASS macro can be considered a mixin. Source SDK uses mixins extensively to standardize the data-access code and ascribe behaviors to entities.

Karl the Pagan