Extending D's support for object-oriented design with private(this)
Steven Schveighoffer
schveiguy at gmail.com
Fri Apr 26 16:38:54 UTC 2024
On Thursday, 25 April 2024 at 05:37:24 UTC, NotYouAgain wrote:
> (2) It allows for accidental, unintended use of a private
> member by other code in the module, including unittests.
>
> // --
> module m;
>
> class C
> {
> private int _count; // visibilty of this member extends
> to the entire module.
> public void setCount(int c) { _count = c; }
> }
>
> unittest
> {
> C c = new C();
> c._count = 42; // Actually, this is a mistake, and the
> programmer should be testing the public method setCount(..)
> }
```d
module m;
class C
{
private(this) int _count;
public void setCount(int c) { _count = c; }
unittest
{
C c = new C();
c._count = 42; // oops, this is still allowed
}
}
```
1. unittests being able to examine/manipulate private data is
*expected* and *desired*. How else do you plan to validate things
are happening properly without having to expose more public
functions than necessary? I'd expect a line such as
`assert(c._count == 0);` to be a valid line in a unittest.
2. unittests generally are placed close to the things they test,
and in fact are required to do so for documented unittests. This
means they will be inside the class, and still have access to
`private(this)` data.
I don't find the arguments compelling enough to make this new
feature. An entire module is as examinable as an entire class
definition. It's already open in your editor even.
-Steve
More information about the dip.ideas
mailing list