Do mixins solve fragile base class issues?
Asked Answered
H

1

6

In a class on programming languages, my professor quotes mixins as one of the solutions to the fragile base class problem. Wikipedia also used to list (Ruby) mixins as a solution for the fragile base class problem, but some time ago someone removed the reference to mixins. I still suspect that they might somehow have an advantage over inheritance with regards to the fragile base class problem. Otherwise, why would a professor say that they help?

I'll give an example of a possible problem. This is a simple Scala implementation of the (Java) problem that the professor gave us to illustrate the problem.

Consider the following base class. Assume that this is some very efficient special implementation of a list, and that more operations are defined on it.

class MyList[T] {
    private var list : List[T] = List.empty
    def add(el:T) = {
        list = el::list
    }
    def addAll(toAdd:List[T]) : Unit = {
        if (!toAdd.isEmpty) {
            add(toAdd.head)
            addAll(toAdd.tail)
        }
    }
}

Also consider the following trait, which is supposed to add size to the list above.

trait CountingSet[T] extends MyList[T] {
    private var count : Int = 0;
    override def add(el:T) = {
        count = count + 1
        super.add(el)
    }
    override def addAll(toAdd:List[T]) = {
        count = count + toAdd.size;
        super.addAll(toAdd);
    }
    def size : Int = { count }
}

The problem is that whether or not the trait will work depends on how we implement addAll in the base class, i.e. the functionality provided by the base class is 'fragile', just as would be the case with a regular extends in Java or any other programming language.

For example, if we run the following code with MyList and CountingSet as defined above, we get back 5, whereas we would expect to get 2.

object Main {
    def main(args:Array[String]) : Unit = {
        val myCountingSet = new MyList[Int] with CountingSet[Int]
        myCountingSet.addAll(List(1,2))
        println(myCountingSet.size) // Prints 5
    }
}

If we change addAll in the base class (!) as follows, the trait CountingSet works as expected.

class MyList[T] {
    private var list : List[T] = List.empty
    def add(el:T) = {
        list = el::list
    }
    def addAll(toAdd:List[T]) : Unit = {
        var t = toAdd;
        while(!t.isEmpty) {
            list = t.head::list
            t = t.tail
        }
    }
}

Keep in mind that I am anything but a Scala expert!

Hols answered 23/1, 2013 at 17:36 Comment(2)
Well maybe it's just me but I don't see how traits/mixins solve fragile base class issues. They have many other qualities though.Imprecision
I do not see it either, so it's not just you :). If they're indeed of no help, it might be really difficult to answer my question... I am willing to accept a 'your professor is wrong' solution as long as it is convincing. Maybe it has something to do with traits not being 'real mixins'?Hols
R
8

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.

Where traits really get you out of trouble is where you already anticipate 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 IndexedSeqOptimized is used to not just indicate but also implement various operations in a way that performs well when indexing is as fast as any other way to access elements of the collection. ArrayBuffer, which wraps an array and therefore has very fast indexed access (indeed, indexing is the only way into an array!) inherits from IndexedSeqOptimized. In contrast, Vector can be indexed reasonably fast, but it's faster to do a traversal without explicit indexing, so it does not. If IndexedSeqOptimzed was not a trait, you'd be out of luck, because ArrayBuffer is in the mutable hierarchy and Vector 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).

Thus, your fragile base class problems are not solved; if you change, say, Traversable's implementation of an algorithm so that it has O(n) performance instead of O(1) (perhaps to save space), you obviously can't know if some child might use that repeatedly and generate O(n^2) performance which might be catastrophic. But if you do know, it makes the fix much easier: just mix in the right trait that has an O(1) implementation (and the child is free to do that whenever it becomes necessary). And it helps divorce concerns into conceptually coherent units.

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.

Rattoon answered 23/1, 2013 at 18:50 Comment(9)
"can completely" -> I think you meant "cannot". Also I still do not understand what is special about traits that makes them better, even partially (you say "it helps", and can "get you out of trouble"), than an abstract class at preventing fragile base class issues. Your arguments for IndexedSeqOptimized would apply just as well if it was an abstract class, no? The fact that it's a trait makes it more general and frees you from a rigid hierarchy (allowing you to mix it at different points of the type hierarchy), but how is that related to aleviating the fragile base class problem.Imprecision
@RégisJean-Gilles - I have tried to clarify. The point is just that you can use traits wherever you need them to provide self-consistent functionality that can work around known implementation differences. Abstract classes can only be used once, so they don't really let you solve the problem (except by going completely orthogonal: "compose, don't inherit").Rattoon
Well, OK, but the fact that traits are applicable in more situations than abstract classes does not affect the issues with fragile base class/base trait. If anything, the problems are just visible in more situations with traits. I still have the feeling that the more general applicability of traits is orthogonal to the fragile base class issues and the possible ways to mitigate them.Imprecision
@RégisJean-Gilles - When an abstract class could solve the problem but you cannot possibly use it due to multiple inheritance then being able to use a trait to do the same thing absolutely is helping the issue. Of course, since traits make composition easier, you may also suffer more from the fragility of your base classes since you rely more upon their robustness. A double-edged sword, perhaps, but not orthogonal.Rattoon
It seems we have an understanding problem. Either I'm having communications issues, or understanding issues (or I'm too tired to see the obvious?), dunno yet :). Let me try again. You say "being able to use a trait to do the same thing absolutely is helping the issue". It certainly solves one issue, but that issue has nothing to do with the specific issues of fragile base class. If we can't agree on this one, I'll just leave it at that. Hopefully we'll get another answer that will either give another stance at it, or explain the same view as yours in a way that I can understand and agree with.Imprecision
@RégisJean-Gilles - My point is that there is no magic anti-fragility wand. You solve the problem through careful design. The issue is one of operational dependences; if you don't even notice that there's a problem, you're still stuck. If you do notice but do not have traits, you're still stuck having to independently work around the problem in every child class. With traits, you can encapsulate the behavior you want and deploy it widely; if the base class changes, look at the trait not everything. But nothing will save you from a poorly-designed base class that is changed carelessly.Rattoon
I'm going to accept this, even though I do not fully understand the answer. They way I see it, traits might make the problem worse in the sense that they are used more extensively than inheritance. It can also be difficult to see which trait exactly breaks the class, as there can be many of them and they can influence and even break each other. They are, however, very useful and using them you can design flexible applications in which the fragile base class problem does not occur.Hols
@Hols - I think that's a fair characterization. They can be part of the problem or part of the solution or both, depending on how you deploy them. They do at least provide a path towards a (partial) solution which is unavailable if you do not have traits.Rattoon
Are interfaces really susceptible to the fragile base class problem? Afterall, there is no implementation to rely upon or override.Saturate

© 2022 - 2024 — McMap. All rights reserved.