On Sunday, 28 January 2024 at 04:23:06 UTC, Steven Schveighoffer
wrote:
..
the unittest case is also similar -- what happens if you put
the unittest next to the function being tested? It's now in the
class, so it can access "true" private data. Same problems,
this even can happen in Java. I don't see what the difference
is. Same code, same file, just in a different spot? Seems more
like you just need to... not do that.
-Steve
There certainly are things you should not do.
There are also things you want the compiler to stop you doing.
And when you use a programming language, where mutable state
automatically, by default, and at all times, leaks out of the
type into the rest of the module, you may really appreciate the
compilers help sometimes.
That's where private(this) comes in handy.
Now this example is pretty small, but imagine debugging this when
foo() is all the way down on line 3546!
The intent should be right there in the design of the type.
Intent should not be subject to analysis of all the code in the
module.
No need to debug this program below, since it will not even
compile.
module test;
@safe:
import std;
class C
{
private(this) int x; // intent: other code in this
module cannnot mutate this.
private(this) int y; // intent: other code in this
module cannnot mutate this.
invariant () { assert (x == y); }
void modifyX() {...}
void modifyY() {...}
}
void foo(C c)
{
c.x = 10; // compiler will not compile this code.
c.modifyX();
}