Interface Limitations in D

Alexandru Ermicioi alexandru.ermicioi at gmail.com
Mon Sep 20 08:32:46 UTC 2021


On Sunday, 19 September 2021 at 20:00:11 UTC, Elmar wrote:
> * **`interface`s do not permit overriding defaults**
>
>       D's interfaces don't allow default implementations of 
> static and non-static functions unlike Java. This makes class 
> implementations more verbose and promotes code duplication 
> because you need to repeat the default implementation in every 
> implementing class, even if you don't care.
>       Java uses the `default` keyword as attribute to allow for 
> overriding a default-implemented interface method.
>
>       Default methods are most important for the ability to 
> extend interfaces without requiring old classes to implement 
> newly added methods and without introducing stateful behaviour.
>       A partial workaround for the extensibility problem is the 
> definition of a new interface which also contains the old one.
>
>       If constant declaration syntax (as previously mentioned) 
> would be added to `interface`s, then runtime constants with 
> default value or without any value could be polymorphically 
> overridable within `class`es (overridden with a different 
> constant value). When they are overridable (e.g. using the 
> `default` keyword, opposite to `abstract`), they could be 
> syntactic sugar for niladic functions which return a constant 
> value and **optionally** could do a one-time-computation of the 
> return value when the static-constant-function is called the 
> first time.
>
>       Abstract classes are no replacement because, first, you 
> cannot inherit multiple abstract classes and, second, abstract 
> classes implement partial incomplete behaviour while interfaces 
> don't implement behaviour.

You can use mixin template that will contain default 
implementation of an interface.

You can also declare final functions in interfaces, which can 
partially serve for first case mentioned.

Best regards,
Alexandru



More information about the Digitalmars-d mailing list