Rethink OOP access permissions

NotYouAgain NotYouAgain at gmail.com
Sun Apr 28 08:15:14 UTC 2024


On Sunday, 28 April 2024 at 07:30:13 UTC, Daniel N wrote:
>
> By solving more than one usecase, the feature might appeal to 
> more people.

fair enough.

Perhaps we need both private(this) and protected(this).

This unittest below will pass, but it really should not.

That's because not just private, but also protected, is public 
inside the module.

It one really must put one class in a module, and unittests in 
their own module as well,
just to get the assurances of correctness, that other languages 
can already provide.

D really is module-oriented-programming, not 
object-oriented-programming.

module m;

unittest
{
    import std;

    ColoredPoint c = new ColoredPoint(2, 4);

    writefln("%s : %s", c.x, c.y); // 2 : 4

    c.reset(); // actually this shouldn't even be allowed. It is 
not in the intent of the design.
    c.clear(); // only the clear() method should be using reset()

    writefln("%s : %s", c.x, c.y); // 0 : 0

}

// Based on some code from: 
https://docs.oracle.com/javase/specs/jls/se22/html/jls-8.html
// I've change a few things though.

class Point
{
   private int x, y;

   this(int x, int y)
   {
       this.x = x;
       this.y = y;
   };

   protected void reset() { this.x = 0; this.y = 0; } // In D, 
protected means accessible to subclass,
                                                      // and ALL 
other code within the module!
                                                      // But 
clearly the intent here is for only the sublcass to access it
                                                      // via it's 
public clear() method - which calls its base reset() method.
                                                      // Other 
code in the module should not be accessing this reset() method.
                                                      // But there 
is no way in D to express that intent.
}

class ColoredPoint : Point
{
     this(int x, int y)
     {
         super(x, y);
     };

     void clear() { reset(); }
}



More information about the dip.ideas mailing list