Friends in D, a new idiom?

IntegratedDimensions IntegratedDimensions at gmail.com
Sun May 27 05:25:53 UTC 2018


(Please don't respond if you are going to attack me in any way! I 
only accept answers that are meaningful to me and if you come up 
with the wrong answer don't get offended when I tell you it's 
wrong, if you do, expect to to get it thrown back in your face)

Was having to restrict write access to a type, for safety, in 
general but required access by some types.

The idea is to supply the write assessors through a sub-interface:

module m;

class C
{
	protected int x = 0;
	@property int X() { return x; }
	protected @property int X(int v) { _this.x = v; return v; }
	public struct _Access
	{

		@property int X(int v) { _this.x = v; return v; }
		C _this;
	}

	_Access Access;

	this() { Access._this = this; }

}








import std.stdio, m;

void main()
{

	C c = new C();

	writeln(c.X);
	c.Access.X = 4;
	writeln(c.X);

	getchar();

}


Here Access has the public setters and so any writing must occur 
through it.

Initially I thought nested classes contained an inherent super 
but I guess that is not the case?

I imagine that the pattern could be extended to really 
encapsulate types better by separating write and read access. By 
forcing write access through another deference, it prevents easy 
write access and hence less use and makes it more explicit.

I also imagine that one could enhance this so that write access 
could also be allowed by certain types.

Any ideas about this type of pattern, how to make it better, 
already exists etc?




More information about the Digitalmars-d mailing list