The D language pays certain attention to avoiding hijacking [1]. So I was surprised when I hijacked a function override from a template mixin by mistake. Here is a commented example. The comments explain the relevant part of the life cycle of the program.

-----
// Start with class A with method fun returning "A".
class A {
    string fun () {return "A";}
}

// Subclass B will return "B" instead.
class B: A {
    override string fun () {return "B";}
}

// Turns out a common need is to return "MT",
// so we will create a mixin template MT for it
// to reduce boilerplate.
mixin template MT () {
    override string fun () {return "MT";}
}

// We use MT in our new subclass C.
class C: A {
    mixin MT;
}

// Both a mixed-in override and a regular one
// by a refactoring mistake, what happens?
class D: A {
    mixin MT;
    override string fun () {return "D";}
}

// Let's find out.
void main () {
    import std.stdio;
    writeln (new B ().fun ()); // B
    writeln (new C ().fun ()); // MT
    writeln (new D ().fun ()); // D, not MT
}
-----

I'd expect a "multiple overrides of same function" error, much like if I just paste the mixin code by hand. Is that a bug or working by design? In the latter case, please explain the reasoning.

Also, if there is a "better" tool than a template mixin in the situation explained in the comments, please point me to it.

[1] http://dlang.org/hijack.html

Reply via email to