Using closure in function scope to make "real" private class members

Commander Zot no at no.no
Wed Jun 8 22:14:52 UTC 2022


On Wednesday, 8 June 2022 at 00:12:28 UTC, forkit wrote:
> On Monday, 6 June 2022 at 11:45:31 UTC, Dom Disc wrote:
>> On Monday, 6 June 2022 at 02:35:11 UTC, forkit wrote:
>>> On Monday, 6 June 2022 at 01:23:41 UTC, forkit wrote:
>>>>
>>>
>>> when your boss isn't really your friend:
>>>
>>> // ----
>>>
>>> module test;
>>> @safe :
>>>
>>> class Employee
>>> {
>>> }
>>>
>>> class Boss
>>> {
>>> }
>>>
>> Now that is real nonsense! Why should those two classes ever 
>> be within the same file?!?
>>
>
> The two classes were clearly concocted for the example - 
> actually, after a discussion with a friend about problems they 
> were having with their boss - who pretended to be friend to 
> them, until one day ....
>
> But that aside, it is often that one object cannot exist, 
> unless the other object already exists.
>
> It's not unusual, to want to keep this code together - even, 
> god forbid, in the same module!
>
>> Not everything is a friend - only what is in the same file!
>
> Precisely. That's my whole point. Everything in the same file 
> is your friend. Although, that is not the actual problem, since 
> friends are useful. The actual problem is there is 'no option 
> to unfriend'.
>
> There are no encapsulated components in a module. The D 
> language doesn't provide the means to do that. It's all just 
> one big... thing.

interface Foo {
     int itWorks();

     static Foo _new() {
         static class PrivateFoo : Foo {
             int _b;
             override int itWorks() { return _b; }
         }
         auto pfoo = new PrivateFoo;
         pfoo._b = 42; //only accessible in this function scope
         return pfoo;
     }
}

int main() {
     auto foo = Foo._new;
     writeln(foo.itWorks);

     return 0;
}


More information about the Digitalmars-d mailing list