When would you want to import a single method? I would just rely on normal inheritance, probably. Otherwise, I want to import a whole pack of methods at a time (Ruby):
Code: Select all
Now I can use my list as I would any other, with #map, #inject, #find, etc. Note that Enumerable only works for classes with #each. Mix-ins typically trust the programmer to provide one or more core methods that are built upon by the mixed-in module, so they're kinda like Java's interfaces (Collection, List), but don't force you to implement all of the convenience methods yourself (although you can override them if you want, for efficiency, etc.) or to put that added functionality in a separate util class. Enumerable is kind of like an abstract class (AbstractList), too, but it doesn't restrict the inheritance heirarchy. It's also not quite multiple inheritance, because only modules can be mixed in, which are not instantiable.
You'd want to import just a single method when you are importing from
two modules that both have something with the same name and they are names
are clashing with each other. In Python you can do:
And pull in the whole namespace if you like. This is considered bad form
in a larger application though, where the style is to import one name
per line. Yes, you get a large block of imports, but it's really easy to
search for a name and see *exactly* where it's coming from.
Python has mix-ins as well (and they are also called mix-ins). They are just Classes that are only intended to be added to other Classes. This does the same thing as the Ruby example:
Code: Select all
Yet, I'm interested in what cases true multiple inheritance would be more desirable. It seems to be more dangerous, though.
Python multiple inheritance versus Ruby's mix-in mechanism are implemented
quite differently, but as far as an application programmer is concerned they
work and feel the same. As to which is more dangerous, the answer is "both".
They can both produces headaches in debugging and understanding code. The both
make it to easy to produce dependancies that can cascade through your code in
unexpected ways. Which is not to say that either technique is bad - they are
both very useful, but if they should not be relied upon to solve all problems,
especially in larger code bases.
Python allows for Object Composition with Interfaces and Adapters (aka Aspect Oriented Programming), as provided by the Zope Component Architecture. This is what Plone 3 uses, and it is a much cleaner, more explicit way than making heavy use of mix-ins. Having been involved with Plone since the early days, and worked with the code base when it was all done with multiple inheritance versus object composition, object composition is a much nicer way of constructing large applications.