Extending D's support for object-oriented design with private(this)

Arafel er.krali at gmail.com
Sat Apr 27 08:29:46 UTC 2024


On 27/4/24 9:39, Jonathan M Davis wrote:
> What I'm saying is that there isn't actually a problem that needs solving.
> It's a theoretical issue and not one in reality. Programmers routinely
> program in D without running into any issues with private. Some of them even
> think that private is private to the class or struct and are surprised years
> later to find out that it isn't, because they never have problems with it.

Well, I'm one of these programmers that was bitten by this issue. Coming 
from Java, though, the idea of keeping a class per file / module didn't 
seem so alien, so I just went with it.

That being said, I would have very much preferred to have this feature 
available.

Another aspect not being discussed here are synchronized classes [1]. 
Note that:

 > Member fields of a synchronized class cannot be public

This breaks apart in very subtle and hard to detect ways when you allow 
other code in the same module to access private members, even if it 
looks innocuous. Concurrency bugs are notably hard to detect and even 
harder to debug, and introducing backdoors like this doesn't exactly help.

And "just don't do it" seems quite a bit like "you're holding it wrong". 
That's just enforcing by convention, and at that point why not go with 
the python "private" way? Just tell people that they shouldn't do it, 
and done.

Note how this is totally opposite as how `const` is treated: no more 
"logical const", but hard const.

Now, you can argue that synchronized classes are a mistake, shouldn't 
exist in the first place, are misleading, whatever... but I also 
disagree here: they have their usage for simple use cases with POD-like 
objects that _need_ to be a class (for whatever the reason).

And the fact is that they exist, so unless and until you deprecate them, 
why not try to make them at least somewhat useful? FWIW, in my view they 
should also implicitly cast to / from shared as needed, just like 
immutable. Anyway, I digress.

So this is another real benefit of having private(this). If the only 
drawback is the hypothetical "complexity" that it could add (which, 
while not being a compiler expert, I very much doubt it would be too 
big), why not check the already existing implementation and see what 
corner cases really appear?

I mean, the feature is literally already implemented, can be tested, and 
some people must be already using it without big issues. Why not at 
least put it behind a preview switch?

[1]: https://dlang.org/spec/class.html#synchronized-classes


More information about the dip.ideas mailing list