Sealed classes - would you want them in D?

Mike Parker aldacron at gmail.com
Sat May 12 16:42:06 UTC 2018


On Saturday, 12 May 2018 at 15:48:53 UTC, KingJoffrey wrote:

>
> Actually, that is not true. If it were true, then I could do:
>
> ------------
> module test;
> void main() { i = 2; }  // sorry, but i belongs to another unit 
> of encapsulation
> void foo() { int i = 1; }
> ------------
>
> D only breaks the encapsulation properties of classes, not 
> functions.

> But that's why we have functions and classes - which are their 
> own level of smaller units of encapsulation. Blurring the 
> boundary of encapsulation seems like a big step backward in 
> terms of structured programming.
>
> Each unit of code (a function, a class, a module) should 
> respect the encapsulation properties of each other.

Encapsulation and scope are not the same thing.

>
> There's simply no point in using classes in D, as they have no 
> capacity to encapsulate themselves

Yes, they do. The private API is not visible to the outside world.


>
> Now if 'private' meant 'private to the class' (as most people 
> would rightly expect), and the default if you had no attribute 
> was, say, 'accessible to the module', then I could probably 
> live with that, and I would start to use classes in D 
> productively.

I'm using classes productively right now. Having private class 
members accessible in the module is a boon, not a hindrance, IMO.

>
> But when the class has lost its capacity to encapsulate, it's 
> lost its purpose.

It hasn't lost its ability to encapsulate. The private 
implementation is hidden from the outside world and does not 
impact the public API.

>
> Making us hold whole modules in memory so we can reason about 
> the interaction between classes and modules, is just nonsense, 
> in my opinion.

No, nonsense would look like this:

```
module mymmod;

class Foo {
    private int _x;
    /* module private */ int x() { return _x; }
}

class Bar {
    private int _y;
    /* module private */ int y() { return _y; }
}

void printFooBar(Foo f, Bar b) {
    import std.stdio : writefln;
    writefln("f.x = %s, b.y = %s", f.x, b.y);
}
```

Thank goodness we don't have to do this silliness.





More information about the Digitalmars-d mailing list