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

Mike Parker aldacron at gmail.com
Fri May 18 12:32:30 UTC 2018


On Friday, 18 May 2018 at 12:16:55 UTC, aliak wrote:

> You may not need a new word at all. You can also enhance 
> private to take arguments. Package already does this. You can 
> give private a symbol list that says which symbols this is 
> private for. So:
>
> class A {
>   private int x;
>   private(A) int y;
> }
> void main() {
>   A a = new A();
>   a.x = 7; // ok, it's private to module
>   a.y = 3; // error, it's sealed to class
> }
>

That's actually a decent way to go about it. It matches the 
package syntax and avoids new keywords. It's also not as onerous 
as repurposing an existing keyword (like `module`), nor does it 
cause any breakage. Though, I would argue that rather than 
allowing any old symbol, it be restricted to `this`:

private(this) int y;

This keeps the implementation simple and the scope focused. If a 
DIP were put forward, I think this would be the approach to take. 
Though a fairly strong case will still need to be made as to why 
this is beneficial (use cases, example code, etc). To bolster the 
case, I would look at the reasoning behind the recommendation in 
Java that classes use the public API internally rather than 
manipulating member variables directly to improve maintainability.




More information about the Digitalmars-d mailing list