Extending D's support for object-oriented design with private(this)

NotYouAgain NotYouAgain at gmail.com
Sat Apr 27 07:31:10 UTC 2024


On Saturday, 27 April 2024 at 06:48:47 UTC, Jonathan M Davis 
wrote:
>
> ...

What is your solution to the problem below?

Let me guess:
(1) don't make the mistake of bypassing the public interface in 
the unittest.
(2) put the unittest in a separate module.

My solution:
(1) make x and y private(this) and you cannot make a mistake, 
since the compiler will not let you make that mistake.

// ---

module m;
@safe:

class C
{
     private int x, y;

     invariant()
     {
         assert(x == y);
     }

     void modifyX(int val)
     {
         x = val;
     }

     void modifyY(int val)
     {
         y = val;
     }
}

unittest
{
     C c = new C();
     c.x = 10; // incorrect use of the type.
}
// ---


More information about the dip.ideas mailing list