[fpc-pascal] Traits Proposal

Martin Frb lazarus at mfriebe.de
Fri Feb 19 03:04:51 CET 2021


On 18/02/2021 23:47, Ryan Joseph via fpc-pascal wrote:
>
>> On Feb 18, 2021, at 12:33 PM, Martin Frb via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>>    TMyFoo = class(specialize TTrait<TFooBase>)
>>       procedure Foo;
>>    end;
>>
>> Of course that can get out of hand, if you want to include many traits.
> I'm not really understand this at all. You're still using subclassing, which is the thing we're trying to avoid.
>
Yes and Yes, and maybe Why?

I agree that a dedicated traits solution would be cleaner, and may have 
advances.
For example in the above, the trait can not have a base-trait. (Well it 
can, but it get messy, really messy).
Multiple traits via generic => messy.
And also the conflict resolution behaviour differs.
...


However what is the problem of the subclassing?

1) From the user of the class (the person using the class in their code) 
all methods are in the desired namespace.

2) There is (almost) no performance penality.
Well perfomance:
   SomeFoo is TXXXX will need to step the extra classes inbetween.
   And so will  fpc assert objec checks, if enbled. (but thats debugging)

But otherwise I can't think were the resulting class would even need one 
CPU tick more. Calling a method (with the exact same signature) should 
generate the exact same code, independent if it was declared in the 
current or in the base class. (at least if it is not 
overriden/reintroduced in the current, but then you would need to call 
it with the "inherited" keyword, so that would be different.)
none virtual method => known address, just call
virtual method => address from know offset in the VMT. In both cases the 
VMT of the current class. Same thing.


And yes, their is memory. Their is one single block of memory for the 
class data. (It is only once, even if you have 1000 instances). So what?

One could have a WPO optimization, to remove classes from the tree, if 
they are not needed.
- no reference to the class itself: casting, ".. is .." (not possible 
here, since anonymous)
- access via ClassType, ParentClassType etc
- no difference in the VMT compared to the next higher class
- not sure maybe others
But its a lot of work in order to save a few bytes in the exe.


More information about the fpc-pascal mailing list