Sealed classes - would you want them in D?

Mike Parker aldacron at gmail.com
Tue May 15 05:59:44 UTC 2018


> (and don't tell me it does - cause the code below clearly 
> demonstrates that it does not)
>
> =======
> module test;
>
> void foo()
> {
>     Person p = new Person("King Joffrey");
>
>     // this completely bypasses my interface
>     // (i.e. the boundary that I set up between the class and 
> the module)
>     p._name = "New King";
>
> }
>
> class Person
> {
>     private string _name;
>
>     public void setName(string name)
>     {
>         this._name = name;
>     }
>
>     public this(string name)
>     {
>         _name = name;
>     }
>
> }
>
> ================================

Jonathan's right. We're just not going to agree on this. The 
implementation is still encapsulated behind the public interface. 
If you don't want main to access Person's private members, then 
don't put them in the same module. Period.

Modules are a cohesive unit, not simply a means of grouping 
related constructs. If the latter is all you're using them for, 
then the solution is simple. Given the following:

module foo.bar.baz;

class A {}
class B {}
class C {}
void funca() {}
void funcb() {}

You can keep your grouping and get your strict encapsulation like 
so:

// foo/bar/baz/package.d
module foo.bar.baz;
public import
     foo.bar.baz.a,
     foo.bar.baz.b,
     foo.bar.baz.c,
     foo.bar.baz.funcs;

The client need neither know nor care that everything is in 
separate modules and you get your strict encapsulation. You can 
still share items between modules via package protection, and 
within specific package hierarchies via package(packageName). And 
even better, you now have less code per module to reason about 
(re: one of your earlier arguments against the current behavior).


More information about the Digitalmars-d mailing list