Tuesday, September 12, 2006

revenge of multiple inheritance

I count myself fortunate to not know much about C++, in spite of that being the language I learned in college (4-yr degree). One of the many details I was blissfully unaware of was multiple inheritance. In fact, I didn't know that C++ supported multiple inheritance until I read about Java interfaces. A statement similar to "interfaces are Java's response to multiple inheritance in C++" usually appeared in the introduction. That inspired me to read about multiple inheritance in C++, but when I encountered the term "virtual base class", I decided to give up on that. The moral I learned was that, as with biology, tangled-up inheritance trees don't work well in practice.

When I started to pick up Python, I was startled to find multiple inheritance sitting right there in plain view, and no one was complaining. Actually, I could have found multiple inheritance in Perl, but that would have never happened because I only used objects in Perl; I never implemented them (is that like saying, "I never inhaled"?). This is a clear instance of the oft-observed difference in values between these languages and Java. In Java, you make the language simple enough that programmers, especially those on teams other than yours, won't mess the code up by abusing complicated features. In these other languages born from scripting, you make the language capable of anything, or at least extendible, so the programmer can do whatever he wants to get his job done. The relevant quote is "easy things easy and hard things possible".

The reason I bring up multiple inheritance now is because of a great blog post by chromatic about Roles: Composable Units of Object Behavior. The concept of object roles is slated for Perl 6. chromatic goes into great detail about how roles basically work as a middle ground between Java interfaces and C++ multiple inheritance. Squint enough and one might even think of it as AOP for classes. There's no reason someone couldn't accomplish a subset of the same effects in existing OO languages using a design pattern or two, but as chromatic explains, there are benefits to having roles built into the type system. Having roles built-in means that an interface and a default implementation don't need to be a matched pair, as in Java, but a single unit that can be applied to a class and checked at compile time or at run time. I still think I would rather have one class, parameterized by constructors into specific objects, and perhaps combined with another class using the decorator pattern, rather than one class parameterized by many roles into many classes. But maybe I'm stuck in the wrong paradigm. Roles seem like a great answer to the quandary of multiple inheritance. Leveraging the compiler is good. Code reuse is good.

No comments:

Post a Comment