Using closure in function scope to make "real" private class members

forkit forkit at gmail.com
Mon Jun 6 02:35:11 UTC 2022


On Monday, 6 June 2022 at 01:23:41 UTC, forkit wrote:
>

when your boss isn't really your friend:

// ----

module test;
@safe :

class Employee
{
   private:
     double salary;

   public:
     double getSalary()
     {
         return salary;
     }

     void setSalary(double amount)
     {
         try
         {
             if (amount < 100_000 )
                 throw new Exception("msg");

             salary = amount;
         }
         catch (Exception e)
         {
             import std.stdio;
             writeln("No. Don't be an ass! Try again.");
         }
     }

}

class Boss
{
   private:
     Employee e;
}

// compile with: -main -unittest
unittest
{
     Boss boss = new Boss();
     boss.e = new Employee();

     //boss.e.setSalary(100_000.0); // The objects invariant WILL 
be upheld (at runtime).

     boss.e.salary = 1.0; // oh. what a cu%# of a boss!
                          // If only D had @private - or, if I had 
'remembered' to use the member function

     import std.stdio : writefln;
     import std.math;
     writefln("The employees salary is: %s", 
(isNaN(boss.e.getSalary())) ? (0) : (boss.e.getSalary()));
}

// -----



More information about the Digitalmars-d mailing list