There's more than one way to do things | |
PerlMonks |
Re^3: Inheritance, just say no! Read the traits paper.by Ovid (Cardinal) |
on Aug 04, 2006 at 07:07 UTC ( [id://565616]=note: print w/replies, xml ) | Need Help?? |
This is not "poe-tay-toe versus poe-tah-toe". Inheritance can be useful and it's sometimes appropriate, but it's often a lousy way to build systems, particularly since it tends to constrain code reuse to a given heirarchy. If you think of a class as an something which has a responsibility to cover a problem domain, then this class needs to do everything it needs to do. That sounds like a silly tautology, but what it means is that there's an upward pressure on the size of a class. The more things it needs to do, the larger it tends to get. However, leaving aside the question of responsibilities, we can also think of objects as units of code reuse. As an object of code reuse, it should do as little as possible. What's the sense of using inheritance when you might inherit twelve methods but only need two? What if, instead of ignoring those other methods, you explicitly don't want them? Or what if you use multiple inheritance you discover you have conflicting methods which ordering problems make difficult to call? Heck, what if you discover that you need to call both of the conflicting methods to maintain proper state in your superclasses? Ack! Many languages suggest using SUPER to get around this, but one keyword doesn't resolve which class you want to call, so you wind up with hacks like hard-coding the superclass name in your method and later wondering why things break when you refactor things. Now some of these are issues with poor composition but this is not always the case. Inheritance schemes lead to conflicting pressures of needing both larger and smaller classes. Sure, you can jump through a bunch of hoops to set up delegates to solve problems, but do you really want to do that every time you face this problem? And if you're delegating to another class when you only need a tenth of the features it provides, why even load that other class in the first place? Traits make these problems go away. They're just gone, finished, kaput. If you really want to understand the problems with inheritance and how traits solve them, read this traits paper (PDF). Many people (including me) admit that it can take a few tries to see what's going on, but once you get it, it makes perfect sense. chromatic's article shows how easy it is to use traits. The traits paper I linked to is the smoking gun. Cheers, New address of my CGI Course.
In Section
Meditations
|
|