property magic for inerfaces (please!)

Daniel Keep daniel.keep.lists at gmail.com
Sat Nov 18 16:54:12 PST 2006



Hasan Aljudy wrote:
> Consider the following hypothetical interface:
> 
> interface IPerson
> {
>     IPerson getFather();
>     IPerson getMother();
>     IPerson[] getSiblings();
>     IPerson[] getChildren();
> }
> 
> For practical purposes, it would be nice to have some methods defined in
> that interface, such as:
> 
> bool hasChildren()
> {
>     return getChildren().length != 0;
> }
> 
> but it's not possible to define this method right in the interface.
> (Suppose say we really have to have the thing as an interface and not as
> an abstract class).
> 
> A possible solution is to add it to the interface without defining it,
> 
> interface IPerson
> {
>     IPerson getFather();
>     IPerson getMother();
>     IPerson[] getSiblings();
>     IPerson[] getChildren();
> 
>     bool hasChildren();
> }
> 
> while hoping that all classes implemeting this interface would define
> the method in the same way, i.e.
> bool hasChildren()
> {
>     return getChildren().length != 0;
> }
> ...

There are two ways of doing this, depending on the situation.

The first is to have an abstract base class, which allows you to add
partial implementation.

The other is to provide a mixin for the "default" implementation of
certain methods.  For example:

> interface IPerson
> {
>     IPerson getFather();
>     IPerson getMother();
>     IPerson[] getSiblings();
>     IPerson[] getChildren();
>
>     bool hasChildren();
> }
>
> template MPerson
> {
>     bool hasChildren()
>     {
>         return this.getChildren.length != 0;
>     }
> }
>
> class SomePerson : IPerson
> {
>     mixin MPerson;
>
>     // ...
> }

In this case, SomePerson needs to implement the first four methods, but
hasChildren is implemented by the mixin.  Ruby does something similar
for implementing things like comparison operators, sorting, etc.

Of course, extension methods would be *even cooler*, but this works
right now :)

	-- Daniel

-- 
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list