Why do private member variables behaved like protected in the same module when creating deriving class?

ShadoLight ettienne.gilbert at gmail.com
Tue Oct 30 09:43:54 UTC 2018


On Tuesday, 30 October 2018 at 00:01:18 UTC, unprotected-entity 
wrote:
> On Monday, 29 October 2018 at 22:24:22 UTC, Bastiaan Veelo 
> wrote:
>>
[snip]
>>
>
> If your were sitting on a plane that was running the following 
> D code, you might think differently ;-)
>
> --------
> class Plane
> {
>     private static int MAX_SPEED = 1000;
>
>     public void change_max_speed(int speed)
>     {
>         if(speed >= 1000)
>             MAX_SPEED = speed;
>     }
>
> }
>
> immutable Plane p = new Plane();
>
> // god no! why aren't you using the public interface of the 
> class for this!
> void SetMaxSpeed() { p.MAX_SPEED = -1; }
>
> void Bar() { SetMaxSpeed(); } // mmm...trouble is about to 
> begin...
>
> void main()
> {
>     import std.stdio;
>
>     Bar(); // oohps. thanks D module. we're all going to die!
>
>     // by the time you see this, it's too late for you, and 
> your passengers.
>     writeln(p.MAX_SPEED);
>
> };
>
>
> -------

Cute example, but your proposed solution does not mitigate this 
risk either. Let's say D does indeed have your 'strict' 
definition of private w.r.t. encapsulation.

So, with your definition this program will fail to compile, but 
remember that Joe Coder is actually modifying the module i.e. he 
has access to the source code of class Plane.... so now he does 
this:

  class Plane
  {
      private static int MAX_SPEED = 1000;

      public void change_max_speed(int speed)
      {
          if(speed >= 1000)
              MAX_SPEED = speed;
      }

      // Man, I need to get this finshed; have a movie date with 
Sally!
      public void SetMaxSpeed() { MAX_SPEED = -1; }

  }

  immutable Plane p = new Plane();

  void Bar() { p.SetMaxSpeed(); } // mmm...trouble is about to 
begin...

  void main()
  {
      import std.stdio;

      Bar(); // oohps. thanks D module. we're all going to die!

      // by the time you see this, it's too late for you, and your 
passengers.
      writeln(p.MAX_SPEED);

  };

Note this is all contained to the same module... so quite easy 
for Joe Coder to make _any_change_whatsoever_! If you want to 
avoid this risk you have to encapsulate (even in your case) at 
the module level, and only allow access via the API (maybe not 
even allow access to sources of class Plane and link to a 
critical_resources.LIB/DLL).

The point is that you cannot completely mitigate against this 
type of risk, no matter what form of encapsulation you may have, 
when people have access to all the sources. Hence the need for 
code reviews, unit tests, etc, etc. There are always areas where 
languages have "back doors" (or lets call them doors with weaker 
locks). At this point this threat are really  arguing about a 
personal preferences; it is not a black or white affair.


More information about the Digitalmars-d mailing list