[Tutor] What is a mixin class?
alan.gauld at btinternet.com
Fri Jan 19 01:18:46 CET 2007
"Don Taylor" <nospamformeSVP at gmail.com> wrote
>I have a vague idea what a mixin class is, I would like to get a
> handle on it.
The mixin style of OOP comes from the old (1970's vintage) Flavors
version of Lisp. In Flavors the metaphor was to start with the Vanilla
flavor and mix-in other flavours as you needed.
In Flavors it was common to define lots of small abstract classes
(mixins) and then the application xclass would inherit from as
many mixins as needed. I have seen classes with as many
as 30 or more mixins and absolutely no methods of their own,
they were all inherited.
For this style to work well requires that mixins are type neutral.
Or more specifically they use "Duck Typing", or are protocol based.
That makes languages like Python natural homes for mixins.
Although mixins can inherit from other base classes it is
traditional that they stand alone so that thee is no risk of
double inheritance of a base class and subsequent confusion
in the class dispatch table.
Mixins are particularly uiseful as a way to add common functionality
to groups of classes that are otherwise not related in a type
Error or Security logging is a common application where you can
simply create logging versions of non logging classes by defining
the logging version to inherit from the original class and the logging
mixin. Once that is done you can use the new class exactly like
the old one and get logging without having to write any new code.
The downside is that the heavy use of mixins can be confusing
to debug, introduce unexpected side effects, introduce unexpected
dependency loops and spread bugs across lots of classes - making
them hard to pin down...
> I guess that because of multiple inheritance Python does not need a
> formal way of specifying mixin classes so I presume that there is
> conventional interpretation/coding that is followed for mixin
The original mixins were simply abstract classes in Lisp. Modern
languages wishing to use the concept sometimes add explicit
support for mixin type classes, or more usually just rely on
conventions - such as expecting them to be pure abstract classes.
> So, what constitutes a mixin class and what are the conventional
> ways to
> denote them in code?
Normally I just mention that its intended as a mixin in the doc
Mixin programming is really more a style of OO programming
using multiple inheritance rather than anything special about
the classes themselves.
Author of the Learn to Program web site
More information about the Tutor