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

forkit forkit at gmail.com
Sun Jun 5 22:35:07 UTC 2022


On Sunday, 5 June 2022 at 21:40:18 UTC, Ola Fosheim Grøstad wrote:
> On Sunday, 5 June 2022 at 20:42:59 UTC, Dom Disc wrote:
>> You don't need to re-declare the class. You can simply 
>> overwrite a friend function.
>
> Not exactly sure by what you mean by overwrite, you mean 
> defining the function twice?
>
> Encapsulation does not protect against sabotage, only against 
> mistakes.

+1 .. although the benefits of encapsulation are much greater 
than that.

Encapsulation, along with the concepts of decompostion and 
abstraction, are the three most important concepts in 
programming. None of which are there to protect against sabotage.

Because of the limitation of the human capacity for dealing with 
complexity, we must organise our code into chunks, in this case, 
a class, so that we can capture common properties 'in one place'. 
Now we can reason about it locally.

Also now, even with our limited human capacity for managing 
complexity, we can begin to build up a complex system. Horray for 
the class!

It's hard to have an object in D (and instantiation of a class) 
that has well defined behaviour, when there is no mechanism to 
protect that behaviour (from mistakes -> from surrounding code in 
the same module).

My example with the unit-test demonstrates that. One class per 
module does not solve that problem either btw.

D's approach *includes* the module as an abstraction by which you 
can manage complexity. But it seems to me, that it has come at 
the expense of the class abstaction -> by that I mean, as long as 
there is no way to enforce the invariants of the abstraction -> 
from any surrounding code in same module, then mistakes will be 
made. Even in unit-test code!

And whether or not mistake are in fact made, is irrelevant. The 
fact that mistakes can be made, requires one to audit ALL the 
surrounding code in the module!

So just the option to have a really private property would be 
nice.

It takes nothing away from anyone, and doesn't force anything on 
anyone. It's purely opt-in, and will no doubt, contribute to 
better encapsulation, and hence better software. Ideally, you'd 
choose to default to @private in your programming guidelines, and 
only when this doesn't work for you, should you remove the @. 
This would encourage better encapsulation I believe. Some of 
those D modules in phobos.. grr...!!

On what basis (other than an idealogical objection to 'change'), 
would someone object to such an 'option'?

Just imagine if D had a leaky module abstraction - but you were 
told to deal with that, by avoiding making mistakes ;-)



More information about the Digitalmars-d mailing list