Hi.

Currently, it's possible that, inside a trait's function, use the parent method 
of a class using the trait. This way, not only it's implicitly supposed the 
trait is used in a class having a parent, but also the parent class has such a 
method. It doesn't seem to be a good practice, as stated in the answers of this 
question 
(https://softwareengineering.stackexchange.com/questions/371067/should-a-trait-refer-to-parent-methods).
Also, it's almost impossible to override a parent method (using the same 
signature) using a trait. This is useful if you have to inherit multiple 
classes from a base class, but also override one (or more) of the base methods 
with a common functionality provided by a trait.
There are some workarounds to these problems (specially talking about the later 
one), but they have their own disadvantages:
Define a trait function with the same signature but a different name and use 
it. The main disadvantage is that it's a different method, and is not 
polymorphic.
Do (1), include the trait in the derived class(es), then override the parent 
method in all derived classes and manually call the trait function. Not perfect 
because you have to copy the same code for all derived classes.

Stick with parent:: in the trait function. Implicit and not good (e.g. static 
analyzers and IDEs cannot help).

Change the parent class to use traits. This is not always possible, as it might 
be someone else's code.

Ignore this please: copy and paste the method all over the place.

It's also not possible to use things like insteadof or as when including the 
trait.

Here, I want to propose the concept of explicitly declaring the parent method. 
The way to achieve this is to use attributes for trait functions, e.g. 
#[Override].
It has the advantage of not requiring the redeclaration of the parent method as 
abstract. However, it should be not allowed to use as clause when including the 
trait function, as it's against the definition of overriding a method (i.e. it 
must have the same name and visibility).
Another method is using a new parent specifier (i.e. abstract parent public 
function …), and is more (?) consistent with the current behaviour. However, it 
requires duplicating the parent method signature.
There could be methods using insteadof or as, but they has nothing to do with 
the trait itself, and doesn't fix the problem of implicit declaration of the 
parent method in the trait.
Thanks,
Mohammad Amin Chitgarha.

Reply via email to