Very hacky solution to class private members

bauss jj_1337 at live.dk
Thu Jun 9 11:35:54 UTC 2022


On Thursday, 9 June 2022 at 11:28:57 UTC, bauss wrote:
> On Thursday, 9 June 2022 at 10:59:53 UTC, Mathias LANG wrote:
>> On Thursday, 9 June 2022 at 10:40:01 UTC, bauss wrote:
>>> [...]
>>>
>>> Might as well just make everything public then, right? Why 
>>> stop there. Removing private, protected, package etc. is the 
>>> way to go then?
>>>
>>> [...]
>>
>> I still don't understand why people still don't get this: The 
>> module is the unit of encapsulation in D. If you want your 
>> class to be truly inaccessible, put it in its own module. 
>> Don't follow Phobos' example: Keep your modules small.
>
> But it doesn't always work putting your class in another module.
>
> Because sometimes it's not __all__ members you want to restrict 
> access to, but only some.
>
> And also there are some scenarios where it doesn't even work 
> properly when put into your own module.
>
> Here is an example where it does not work:
>
> a.d
>
> ```d
> module a;
>
> class Foo
> {
> 	private:
> 	int _c;
> }
>
> import b;
> void handle(Bar child)
> {
> 	// This fails even tho we're in module a,
> 	// so _c should be available to us, because
> 	// _c is private to the module (but not really.)
> 	child._c += child.c;
> }
> ```
>
> b.d
> ```d
> module b;
>
> import a;
>
> class Bar : Foo
> {
> 	public:
> 	int c;
>
> 	this(int c)
> 	{
> 		this.c = c;
> 	}
> }
> ```
>
> main.d
> ```d
> module main;
>
> import a;
> import b;
>
> void main()
> {
> 	auto bar = new Bar(30);
> 	handle(bar);
> }
> ```
>
> The above fails to compile.
>
> However this works:
>
> a.d
> ```d
> module a;
>
> class Foo
> {
> 	private:
> 	int _c;
> }
>
> class Bar : Foo
> {
> 	public:
> 	int c;
>
> 	this(int c)
> 	{
> 		this.c = c;
> 	}
> }
>
> void handle(Bar child)
> {
> 	// It's okay now since Bar is in the a module.
> 	child._c += child.c;
> }
> ```
>
> (main.d is the same)
>
> So you can't always split classes into new modules that easily.
>
> It really should work in both cases since we're both accessing 
> _c from within the module, but there's clearly a difference.

Here's a relevant dead DIP for this:

https://wiki.dlang.org/DIP22

As noted, D doesn't even know what private should mean as it 
certainly doesn't mean "private to the module" only.


More information about the Digitalmars-d mailing list