Using memberspaces for a property-like syntax and more
Era Scarecrow
rtcvb32 at yahoo.com
Sat Feb 2 17:45:13 PST 2013
On Saturday, 2 February 2013 at 23:23:37 UTC, TommiT wrote:
> You say "there's no real benefit". I say "there's the benefit
> of being able to add another layer of encapsulation when it's
> needed". Here's what I mean by that:
>
> The lack of encapsulation with @property attribute:
>
> struct T
> {
> private int _value;
>
> void add_twice(int v)
> {
> _value += 2 * v;
> }
> }
>
> struct S
> {
> private T _t;
> private int _sum_of_squares; // Can't update this
>
> @property ref T prop()
> {
> return _t;
> }
> }
>
> void main()
> {
> S s;
> s.prop.add_twice(); // *Not* incrementing s._sum_of_squares
> }
I'd just call that bad design, I wouldn't reference a variable
like that unless it's returned const or I don't care about if
anything else accesses it. Since T/_t is private you shouldn't be
giving access to them without a good reason.
> ...Whereas with memberspaces we can add that extra layer of
> encapsulation:
>
> struct S
> {
> private T _t;
> private int _sum_of_squares;
>
> memberspace prop
> {
> ref const(T) opCall() const
> {
> return _t;
> }
So this one's allowed a const get return....
> void add_twice(int v)
> {
> _sum_of_squares += (2 * v)^2; // Yippee!
> return _t.add_twice(v);
> }
> }
> }
Hmmm curiously the above previous example didn't include
add_twice outside of T. had it of and had a const get I'm sure
these would be about the same.
I'll your example(s) here reflect a bad/different design rather
than why namespaces should be used.
Besides, wasn't namespaces in D handled due to initial modular
setup and alias?
More information about the Digitalmars-d
mailing list