Adding a new design constraint to D

forkit forkit at gmail.com
Sun Jun 26 01:28:46 UTC 2022


On Tuesday, 14 June 2022 at 20:22:17 UTC, Dom Disc wrote:
> On Tuesday, 14 June 2022 at 19:39:40 UTC, Paul Backus wrote:
>> If a function doesn't need access to private member variables, 
>> don't implement it as a member function. Instead, put it in a 
>> separate module and call it using UFCS.
> Yes, that is nice.
> But the most common usecase is that the class has multiple 
> private variables, and each member function needs only access 
> to some of them.
> Today there is no way to express to which of them a function 
> should have access and to which not.
> My idea was the following:
>
> class C
> {
>    private int _hidden_x;
>    private int _hidden_y;
>    @limitPrivateAccess(_hidden_x) foo(x)
>    {
>       _hidden_x = x;
>       _hidden_y = 0; // error: foo has no access to _hidden_y
>    }
> }
>
> So foo would normally have access to _hidden_y although the 
> developer doesn't want that. That is so because today _all_ 
> member functions (and friends) have access to _all_ private 
> variables. The new UDA @limitPrivateAccess restrict this to 
> only those private variables given as its parameters.
> Together with a new privacy-level "@hidden" we could even have 
> variables that no-one has access to, except those functions 
> that are explicitly allowed to access them via the UDA. This 
> would be the ultimate restriction level.

I kinda like this... just as an 'idea', at this stage.

I'm certainly not suggesting we should do it. But discussions are 
always worthwhile.

But some classes can indeed be very long....even necessarily so.

I'd like the concept to make use of the existing invariants() 
method.

i.e some attribute that can only be used, and only makes sense, 
when used in that method.

the ultimate (and only) aim here, is to enhance the provability 
of the program, through static compile time checking (which can't 
be done unless you can first express intent).

e.g:

(and no. I haven't thought this through very much at all).

class C
{
     private(this):
      int x, y, z;

     invariant()
     {
         // restrict certain member functions to certain member 
variables.
         assert( @restrictedMemberAccess {x, y : setXY, getX, 
getY};
     }

     setXY(int x, int y) { x = x; y = y } // fine
     int getX( return x); // fine
     int getY( return y); // fine

     void foo( x = 0; ); // noCanDo! foo is not in the above list.
     void bar( z = 0; ); // fine. no invariants declared. so 
normal rules apply.
}

Destroy!



More information about the Digitalmars-d mailing list