property magic for inerfaces (please!)

Hasan Aljudy hasan.aljudy at gmail.com
Sat Nov 18 15:27:24 PST 2006


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;
}
The main problem with this is that it's not practical more complicated 
functions.

Another solution is to define the function outside of the interface,

bool hasChildren(IPerson dude)
{
     return dude.getChildren().length != 0;
}

The problem with this is that it doesn't feel quiet right when you use it.
...
IPerson guy = .... //something
..
if( hasChildren(guy) )
{
  ....
}

It would be nice if the compiler would allow you to call this method as 
a property (like with arrays)

if( guy.hasChildren() )
{
  ....
}

Can we have this feature before v1.0?
Basically, a function that takes an interface as a first parameter can 
be considered a property of that interface.



More information about the Digitalmars-d mailing list