Sealed classes - would you want them in D? (v2)
Mike Parker
aldacron at gmail.com
Fri May 18 13:44:53 UTC 2018
On Friday, 18 May 2018 at 12:42:05 UTC, KingJoffrey wrote:
>
> How hard is it to convince people, that being able to have the
> compiler detect semantic errors that break your defined
> interface is actually a good thing. I mean really. I've had
> this capability in major languages for decades.
>
> Let D empower the programmer in this case, by giving that back
> to them (as an opt-in)
Two points:
1) the status quo in D is not generally viewed as a violation of
encapsulation (if you change the class, you can also change the
module)
2) there's a simple workaround already in place for people who
really, really, want to do it
The DIP will need to provide counters to both of these points.
One example for point one off the top of my head --
Currently, if you do something like change the name of a private
member, anything in the module still referencing the old symbol
will cause a compiler error and you can fix it immediately.
But, say you have this code:
```
class Foo {
private int _x;
int x { return _x; }
}
void printFoo(Foo f) { writeln("Foo: ", f._x);
```
And later, you decide you want to track all accesses to _x in a
foo instance:
```
class Foo {
private int _x;
private int _xHits;
int x() {
++_xHits;
return _x;
}
// Oops!
void printFoo(Foo f) { writeln("Foo: ", f._x);
```
This would only manifest itself at runtime and in a large module
could be one of those bugs that keeps you scratching your head
for much longer than it ought to. The same thing can happen
through accessing _x internally in the class, but the surface
area is smaller and the bug could (theoretically) be caught more
quickly (and preventing even this is the rationale behind the
Java style of using accessors internally).
So that's the sort of thing a DIP would need to be doing.
Essentially, answering the questions: what are the holes in the
status quo ("encapsulation is violated" doesn't cut it -- solid
examples of real issues are required), and how is the proposed
solution superior to the workaround?
More information about the Digitalmars-d
mailing list