alias this private?

js.mdnq js_adddot+mdng at gmail.com
Sun Dec 9 11:52:10 PST 2012


On Sunday, 9 December 2012 at 19:38:28 UTC, Ali Çehreli wrote:
> On 12/09/2012 11:23 AM, js.mdnq wrote:
>
> > but b is not private, only the internal representation of it.
> e.g.,
> > `alias Value_ this` is public. I do realize that it sort of
> makes Value_
> > and b one and the same but they are not quite the same.
> >
> > To me, it breaks encapsulation. writeln(c.b) is accessing b,
> not Value_.
> > b is a "virtual type" in the sense that it wraps Value_.
> While it seems
> > to do something funky like change the protection of Value_
> from private
> > to public it doesn't. There is no way to access Value_ when
> it is
> > private. i.e., we can't do c.b.Value_;
>
> That's great. Value_ must remain private.
>
> > To drive the point home. We could/should be able to completely
> > encapsulate `Value_` by overriding opAssign and add getters
> and setters
> > so that `Value_` is actually never even used(although
> pointless then).
>
> That is possible in D.
>
> > Another way to see this:
> >
> > struct sPassword
> > {
> > private:
> > string Password;
> > public:
> > alias this Password;
> > opAssign
> > opCast
> > opCmp
> > opGet { return "******"; }
> > Change(old pass, new pass) { if ... }
> > Validate(pass) { pass == Password; ... }
> > }
> >
> > sPassword myPass;
> > writeln(myPass) same as writeln(myPass.Get()) which prints
> ******
>
> You may have a point but at least I need to see how the 
> existing features of D are not acceptable. The following 
> already does what you want:
>
> struct sPassword
> {
> private:
>     string Password_;
>
> public:
>
>     alias opGet this;
>
>     string opGet() { return "******"; }
> }
>
> void main()
> {
>     sPassword myPass;
>     assert(myPass == "******");
> }
>
> (Aside: Although its name may suggest so, opGet is not an 
> operator function.)
>
> > In any case, it just seems to me that we should be able to
> use private
> > this way. If we want the additional functionality we just
> make it public.
>
> Yes, private it good.
>
> > (it does sort of seem sPassword is like a readonly type but
> it's more
> > than that as it encapsulates completely)
> >
> > Now, if Password was public instead of private, anyone could
> do
> > myPass.Password to get the password.
>
> Yeah, not a good idea.
>
> Ali

Well, I would not say they are exactly the same. In your case you 
are aliasing on opGet while I'm talking about aliasing on the 
struct itself. e.g., there might be other members you do want the 
user to have access too. With your's, they won't be able to 
access them(your's is actually more restrictive).

For example, how can they access a "Validate" method like I have 
using your struct?





More information about the Digitalmars-d-learn mailing list