Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Mixins (whether as traits or something else) cannot completely prevent fragile base class syndrome, nor can strictly using interfaces. The reason should be pretty clear: anything you can assume about your base class's workings you could also assume about an interface. It helps only because it stops and makes you think, and imposes a boilerplate penalty if your interface gets too large, both of which tend to restrict you to needed and valid operations.</p> <p>Where traits really get you out of trouble is where you <em>already anticipate</em> that there may be a problem; you can then parameterize your trait to do the appropriate thing, or mix in the trait you need that does the appropriate thing. For example, in the Scala collections library, the trait <code>IndexedSeqOptimized</code> is used to not just indicate but <em>also implement</em> various operations in a way that performs well when indexing is as fast as any other way to access elements of the collection. <code>ArrayBuffer</code>, which wraps an array and therefore has very fast indexed access (indeed, indexing is the only way into an array!) inherits from <code>IndexedSeqOptimized</code>. In contrast, <code>Vector</code> can be indexed reasonably fast, but it's faster to do a traversal without explicit indexing, so it does not. If <code>IndexedSeqOptimzed</code> was not a trait, you'd be out of luck, because <code>ArrayBuffer</code> is in the mutable hierarchy and <code>Vector</code> is in the immutable hierarchy, so couldn't make a common abstract superclass (at least not without making a complete mess of other inherited functionality).</p> <p>Thus, your fragile base class problems are not solved; if you change, say, <code>Traversable</code>'s implementation of an algorithm so that it has <code>O(n)</code> performance instead of <code>O(1)</code> (perhaps to save space), you obviously can't know if some child might use that repeatedly and generate <code>O(n^2)</code> performance which might be catastrophic. But if you <em>do</em> know, it makes the fix much easier: just mix in the right trait that has an <code>O(1)</code> implementation (and the child is free to do that whenever it becomes necessary). And it helps divorce concerns into conceptually coherent units.</p> <p>So, in summary, you can make anything fragile. Traits are a tool that, used wisely, can help you be robust, but they will not protect you from any and all follies.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload