Mixin vs inheritance

OopInheritanceMixins

Oop Problem Overview


What is the difference between a mixin and inheritance?

Oop Solutions


Solution 1 - Oop

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

The detail is that a mixin is rarely useful as a standalone object.

For example, say you have a mixin named "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 mixin IS inheritance. But you can argue it's a matter of the role of the class in the overall domain as to whether a mixin is a "primary" class or simply a mixin.


Edit -- just to clarify.

Yes, a mixin can be considered, in today's 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 mixin any special status; it's just a class that was designed to be "mixed in", rather than used standalone.

Solution 2 - Oop

> # What is the difference between a mixin and inheritance?

A mix-in is a base class you can inherit from to provide additional functionality. Pseudocode example:

class Mixin:
    def complex_method(self):
        return complex_functionality(self)

The name "mix-in" indicates it is intended to be mixed in with other code. As such, the inference is that you would not instantiate the mix-in class on its own. The following object has no data, and it makes no sense to instantiate it to call complex_method. (You may as well just define a function instead of a class in that case.)

>>> obj = Mixin()

Frequently the mix-in is used with other base classes.

Therefore mixins are a subset, or special case, of inheritance.

The advantages of using a mix-in over single inheritance are that you can write code for the functionality one time, and then use the same functionality in multiple different classes. The disadvantage is that you may need to look for that functionality in other places than where it is used, so it is good to mitigate that disadvantage by keeping it close by.

I have personally found a mix-in necessary to use over single inheritance where we are unittesting a lot of similar code, but the test-cases are instantiated based on their inheritance of a base case, and the only way to keep the code close at hand (and in the same module), without messing with coverage numbers, is to inherit from object, and have the child cases inherit from both the universal test-case base and the custom base that only applies to them.

Mixins in Comparison and Contrast with Abstract Base Classes

Both are a form of parent class that is not intended to be instantiated.

A mixin provides functionality, but is unable to directly use it. A user is intended to use it through a (sub)class.

An abstract base class provides an interface, but without usable functionality. A user is intended to create the functionality called by the interface.

class Abstraction(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def complex_method(self):
        return complex_functionality(self)

Here you are prevented from instantiating this object because it requires a subclass to implement functionality with a concrete method (though you could access the functionality within from super()):

>>> obj = Abstraction()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstraction with
abstract methods complex_method

In Python, some classes in the abc module are examples of parent classes that both provide functionality through inheritance and abstract interfaces that must be implemented by the subclass. These ideas are not mutually exclusive.

Summary

Put simply, a mix-in is just a base class you wouldn't instantiate on its own, and typically used as a secondary base class in multiple inheritance.

Solution 3 - Oop

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.

Solution 4 - Oop

Mixin is an abstract concept and anything that meets its requirement can be considered as a mixin.

Here is a definition from Wikipedia.

In object-oriented programming languages, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".

In short, the key difference from an inheritance is that mix-ins does NOT need to have a "is-a" relationship like in inheritance.

From the implementation point of view, you can think it as an interface with implementations. For example, an abstract class in Java could be considered as a mixin if Java supported multiple inheritance.

Solution 5 - Oop

"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.

Solution 6 - Oop

Mixins are vastly used in a more "plugin" like manner.

They are the same but in a different context each one of them. Usually when we talk about inheritance we are talking about SINGLE inheritance, and a mixin is a construct that allows MULTIPLE inheritance.

This is a language construct that is highly controversial in the OOP world because of:

  • The ambiguity that it must be resolved
  • A lot of the time "mixin" classes don't work on its own, and may conflict with other mixins
  • It can result in a "diamond inheritance problem", where two super classes can inherit from the same class

But that aside, is a powerful construct that's used in various languages and frameworks, some examples are:

Solution 7 - Oop

I think its important to note, that mixin doesn't imply inheritance. According to wikipedia, a Mixin is:

> In object-oriented programming languages, a mixin is a class that > contains methods for use by other classes without having to be the > parent class of those other classes. How those other classes gain > access to the mixin's methods depends on the language. Mixins are > sometimes described as being "included" rather than "inherited".

Specifically, in a language like perl, mixins can be added using the Exporter module:

package Mixins;

use Exporter qw(import);
our @EXPORT_OK = qw(pity);

# assumes it will be mixed-in to a class with a _who_do_i_pity method
sub pity {
    my ($self) = @_;
    printf("I pity %s\n", $self->_who_do_i_pity('da foo'));
}

Which can be mixed-in to any module containing one, or more, method(s) at a time:

package MrT

use Mixins qw(pity);

sub new {
    return bless({}, shift);
}

sub _who_do_i_pity {
    return 'da foo!'
}

Then in your MrT module can be used thusly:

use MrT;

MrT->new()->pity();

I know its an absurd example, but, it gets the point across...

Solution 8 - Oop

With multiple inheritance, new class may be composed from multiple superclasses. You can call only methods defined in any of superclasses.

On the other hand, mixin is an abstract subclass that may be used to specialize the beavior of a variety of parent classes. Mixins may call a method (for example sayHello(): String) even though they do not define such a method.

mixin M {
    name: String
    defmethod greetings() { print sayHello() + " " + name}
}

As you see, you can call sayHello() even though it is not defined anywhere. If you add the mixin M to class C, the C should provide the sayHello() method.

Solution 9 - Oop

tl;dr

mixin and multiple inheritance have the same form. But have different semantics: mixin has the basic classes provide the function implementation. For inheritance, base classes provide interface and subclass has the implementation.

But anyway, composition is preferred over mixin IMO

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohndView Question on Stackoverflow
Solution 1 - OopWill HartungView Answer on Stackoverflow
Solution 2 - OopRussia Must Remove PutinView Answer on Stackoverflow
Solution 3 - OopAlex MartelliView Answer on Stackoverflow
Solution 4 - OopAlexView Answer on Stackoverflow
Solution 5 - OopKarl the PaganView Answer on Stackoverflow
Solution 6 - OopggallovalleView Answer on Stackoverflow
Solution 7 - OopLucasView Answer on Stackoverflow
Solution 8 - Oopjk_View Answer on Stackoverflow
Solution 9 - Oopdel baoView Answer on Stackoverflow