note
Ovid
<p>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.</p>
<p>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.</p>
<p>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 <em>don't</em> 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 <em>both</em> of the conflicting methods to maintain proper state in your superclasses? Ack! Many languages suggest using <tt>SUPER</tt> 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.</p>
<p>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 <em>really</em> 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 <em>go away</em>. They're just gone, finished, kaput.</p>
<p>If you really want to understand the problems with inheritance and how traits solve them, <a href="http://www.iam.unibe.ch/~scg/Archive/Papers/Scha03aTraits.pdf">read this traits paper</a> (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.</p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-17000">
<p>Cheers,<br />
<a href="/index.pl?node=Ovid&lastnode_id=1072">Ovid</a></p>
<p><small>New address of <a href="http://users.easystreet.com/ovid/cgi_course/">my CGI Course</a>.</small></p>
</div></div>
565581
565588