DIP23 Counter Proposal

Dan dbdavidson at yahoo.com
Thu Feb 7 12:59:05 PST 2013


On Thursday, 7 February 2013 at 20:26:10 UTC, Jonathan M Davis 
wrote:
> It works as long as you can limit the variable in some way. But 
> I believe that
> the main purpose in using public variables rather than actual 
> property
> functions when all they would do is get or set the variable is 
> to avoid lots
> of boilerplate code. It's incredibly common to get stuff like
>
> struct S
> {
>  int i() @safe const pure nothrow
>  { return _i; }
>
>  int i(int value) @safe pure nothrow
>  { return _i = value; }
>
>  private int _i;
> }
>
> That's a lot of extra code whose only benefit is encapsulation. 
> So, it would be
> great if you could just do
>
> struct S
> {
>  int i;
> }
>
> And with the ability to replace the variable with a property 
> function later if
> it ever needs to do more than just get or set makes it so that 
> encapsulation
> isn't a problem - except for the fact that there are certain 
> operations that
> you can do on a variable that you can't do on a property 
> function (e.g. taking
> its address or passing it by ref). Simply making it so that 
> doing
>
> struct S
> {
>  @property int i;
> }
>
> lowered into something like the first example would allow you 
> to avoid all of
> that boilerplate code and still have full encapsulation.

If it lowered into something like the first example would there 
really be any encapsulation? Wouldn't that be exactly the same as 
public int i?

If this is the goal - to get rid of the boilerplate of accessors, 
it makes sense but a new feature is not necessary.

If you want read/write access to a member but the benefit of 
being able to intercept access in the future start with struct S 
{ int i; }. When the need arises to change the behavior, switch 
to:

struct S {
   int i() @safe const pure nothrow
   {
     // SPECIAL SAUCE
     return _i;
   }

   int i(int value) @safe pure nothrow
   {
     // SPECIAL SAUCE
     return _i = value;
   }

   private int _i;
}

If you don't have any SPECIAL SAUCE then you don't need to switch.

If you want more encapsulation and specifically don't want to 
provide write access, just read access then a mixin can do the 
trick of providing read access to s.i. In the future you can 
change the read accessor and provide one with SPECIAL SAUCE.

struct S {
    mixin ReadOnly!_i;
    private int _i;
}

>
> It's definitely true that you can never make a property 
> function completely
> emulate a variable, but all of the boilerplate required for 
> simple getters and
> setters is kind of ridiculous. I believe that avoiding that is 
> the primary
> reason that people want to be able to swap between variables 
> and property
> functions, and with a small addition to the language, we can 
> obviate that
> boilerplate.
>

No addition needed.

Thanks
Dan


More information about the Digitalmars-d mailing list