Sealed classes - would you want them in D? (v2)

Sjoerd Nijboer sjoerdnijboer at gmail.com
Mon May 21 13:39:12 UTC 2018


On Friday, 18 May 2018 at 15:57:06 UTC, bachmeier wrote:
> class A {
>    private int x;
>    private(this) int y;
> }

Instead of such a syntax if this ever comes to be, we could just 
introduce a new keyword into the language.

class A {
    private int x;
    closed int y; //closed for acces outside this class.
    owned int z; //owned by this class.
    inside int zz; //only accessible inside this class.
}

As far as I can tell we don't need a `private(this)` or 
`private(classname)` declaration. I'd much rather have a keyword 
specifically designed for the thing that it does.

D is at the point that there's already legacy code so you can't 
use the `private` keyword anymore whitout doing something funky 
with defining it private to class scope any other given scope. It 
would also raise the question of "Why can't I have 
`private(functionName)`? Does that make sense?"

I do see how this could be usefull if you had a 6000 line static 
function that you don't want to have access to a private member 
that is defined in thesame module. But then again, one could 
simply extract it to its own module, reference the former module 
and use those classes.

I personally find having no class private members incredibly 
usefull since I can use them for unittests that way.
Then I can enforce the existance of a class member regardless of 
its scope to exist and therefore enforce the use of a given 
approach to the problem a class is solving.
While you might say that a unittest shouldn't acces private 
members and only public members, there are plenty of testcases 
where one would want to write a unittest to set a given variable 
via public function and then test if the appropriate private 
fields are properly set. While this sounds like a trivial usecase 
I believe it to be a verry big one in practice since it removes a 
lot of boilerplate code from your unit-tests, together with 
exposing the innards of a class's implementation to the outside 
world just so you can unit-test it. The last point is something I 
don't like about OOP + TDD in languages like C# or java and I 
think D has (accidentally) solved this in a beautiful way, and I 
would dislike to see this feature go.


More information about the Digitalmars-d mailing list