Real OOP with D

BBasile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 18 00:19:00 PDT 2015


On Tuesday, 18 August 2015 at 06:27:53 UTC, Ozan wrote:
> On Monday, 17 August 2015 at 06:59:51 UTC, BBasile wrote:
>> On Monday, 17 August 2015 at 05:57:52 UTC, Ozan wrote:
>>> Hi
> [...]
>>>
>>> Is there any way to get real OOP with D?
>>>
>>> Regards,  Ozan
>>
>> Can you name an OOP oriented language that allows this ? Your 
>> example is eroneous OOP.
>> The 2 other answers you 've got (the first using an interface 
>> and the second using an abstract class) are valid OOP.
>>
>> One of the fundamental concept OOP is that a function defined 
>> in a class exists also  in its subclasses. So how do you 
>> expect `greeting()` to exist in Family if it's only defined in 
>> its sub-classes ?
>>
>> You can verify that with the 'Liskov substitution principle' 
>> (https://en.wikipedia.org/wiki/Liskov_substitution_principle).
>> Actually your sample violates this principle.
>
> Languages like Groovy or JavaScript (with the help of 
> frameworks ;-)
> And I believe many more the newer ones.  But that's not the 
> point.
>
> And... This was not a criticism against D (... "bad D, has no 
> understanding of OOP. Boahh"  ;-)
> It was only a question about handling of a typical OOP problem 
> in a class-typed implementation of OOP like D has. Thanks to 
> every existing or new creative programming language, today we 
> have so many other ways to solve our programming problems.
>
> Regards Ozan

You example is not valid strongly-typed OOP. In D you could do 
something similar but not with the OO paradigm but rather with 
compile-time refexion (introspection):

---
import std.stdio;

static bool isFamilyMember(T)()
{
     import std.traits: isCallable;
     return __traits(hasMember, T, "greeting");
}

void FamilyMemberSayHello(T)(ref T t)
{
     static if (isFamilyMember!T)
         t.greeting;
}

struct Dad{
     void greeting(){"hello from a Dad".writeln;}
}

struct Boy{
     void greeting(){"hello from a Boy".writeln;}
}

struct IdiotDuBled{}

void main()
{
     auto dad = new Dad;
     auto boy = new Boy;
     auto idiotDuBled = new IdiotDuBled;

     FamilyMemberSayHello(dad);
     FamilyMemberSayHello(boy);
     FamilyMemberSayHello(idiotDuBled);
}
---

The idea is rather to check at compile time if a variable will 
have the "trait" which characterizes a FamilyMember, without 
using inheritence.


More information about the Digitalmars-d-learn mailing list