how to make private class member private

Steven Schveighoffer schveiguy at yahoo.com
Tue Mar 13 13:59:00 UTC 2018


On 3/12/18 10:06 PM, psychoticRabbit wrote:
> On Tuesday, 13 March 2018 at 01:39:13 UTC, Jonathan M Davis wrote:
>>
>> private is private to the module, not the class. There is no way in D 
>> to restrict the rest of the module from accessing the members of a 
>> class. This simplification makes it so that stuff like C++'s friend 
>> are unnecessary. If your class in a separate module from main, then 
>> main won't be able to access its private members.
>>
>> - Jonathan M Davis
> 
> Mmm.. I don't think I like it.
> 
> I feel you should be able to make a member of a class, private, 
> regardless of where the class is located. This seems to break the 
> concept of class encapsulation.
> 
> No. I don't like it at all.
> 

OK, so I agree there are drawbacks. But these can be worked around.

In fact, the language author touted this article as sage advice, when in 
D it's pretty inconvenient: 
https://forum.dlang.org/post/osr2l3$1ihb$2@digitalmars.com

But when you get right down to it, where you draw the line is arbitrary. 
Given the power to encapsulate on module boundary, you have lots of 
different options as to where your functions can reach. You can pretty 
much put anything into a module, so you aren't limited to class members 
which can access specific data. With the advent of package modules, you 
can control quite finely what functions have access to what items, and 
still have nice simple imports.

If you limit to class members, then you have to do something like C++ 
friends, which are unnecessarily verbose.

IMO, the module-level encapsulation is the right choice. It helps with a 
lot of key features:

1. IFTI factory methods
2. unittests
3. co-related structs/classes

-Steve


More information about the Digitalmars-d-learn mailing list