New concept Mixin Methods
Andre Pany
andre at s-e-a-p.de
Wed Dec 28 12:34:13 UTC 2022
On Tuesday, 27 December 2022 at 01:15:42 UTC, Adam D Ruppe wrote:
> On Sunday, 25 December 2022 at 15:29:40 UTC, Timon Gehr wrote:
>> I don't think it's about saving the typing, it's about not
>> allowing bugs to appear because people _forgot_ to type.
>
> This is exactly true... and it brings to mind an alternate
> idea: require a non-abstract method must be overridden in a
> child class.
>
> Consider this:
>
> class Dupable {
> __mustOverride("hint message") Dupable dup() { return new
> Dupable(); }
> }
>
> class Child : Dupable {
> // if you forgot to override dup, you'd get the wrong type
> out
> // but since the parent had mustoverride, the compiler will
> tell us
> }
>
>
> error: class Child must override method `Dupable dup`
> hint: hint message
>
>
> Then it prods them in the right direction and the hint message
> can tell them to mixin something.
>
> Destroy.
While this works, there is a small blurring. We want to express
that a specific mixin template is mixed into the sub class, but
what we actually say is, that a specific method needs to be
overridden. Therefore the developer can just override the method
without actual mixin the mixin template.
From my point of view, it would be neat if I could express that a
specific mixin template should be evaluated within each child
class. In the sample below the syntax `class mixin Foo;` is used.
```d
import std;
mixin template Foo()
{
void fancyMethod(){
writeln(__traits(identifier, typeof(this)));
}
}
class Animal {
class mixin Foo;
}
class Dog : Animal {}
class Bulldog : Dog {}
void main() {
new Animal().fancyMethod();
new Dog().fancyMethod();
new Bulldog().fancyMethod();
}
```
Kind regards
Andre
More information about the Digitalmars-d
mailing list