Using closure in function scope to make "real" private class members
forkit
forkit at gmail.com
Sun Jun 5 06:08:10 UTC 2022
On Sunday, 5 June 2022 at 04:49:44 UTC, forkit wrote:
>
btw.
here is a simple example, for demonstration purposes only, of the
change that I'd like to see in D:
It's benefit seems very obvious to me ;-)
First, the invariants of the class are now upheld by the compiler.
Second, those of us who expect invariants to be upheld, can now
have it.
Third, it's completely optional. Nobody has to change anything
they currently do. If you don't want it, don't use it.
// ----
module test;
// example: @private is an access specifier, that works just as
private does,
// except, that @private is encapsulated to the class (or struct).
class ID
{
import std.string;
@private:
string _id;
public
void setID(string id)
{
assert(isNumeric(id));
_id = id;
}
}
unittest
{
import std.stdio;
ID id = new ID();
id.setID("123"); // Fine. The invariant is maintained.
writeln(id._id);
id._id = "dsa"; // This would violate the invariant.
// The compiler would never allow this with
@private
writeln(id._id);
}
// -----
More information about the Digitalmars-d
mailing list