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

Bastiaan Veelo Bastiaan at Veelo.net
Tue Oct 30 08:18:57 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:
>>
>> I hear you and understand you, but personally I still prefer 
>> the D spec as it is in this regard, except for the confusing 
>> aspect that you shouldn’t `alias this` a private member; but 
>> that is rather a limitation of alias, not of encapsulation.
>>
>
> 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);
>
> };
>
>
> -------

:-) Why is MAX_SPEED mutable or even a runtime value, let alone 
signed?

Anyway, every example you can come up with can be turned around 
and applied to a large class, that is, similar mistakes can be 
made within the class. But let's not repeat arguments. If you 
want to use OO in D you'll just have to flip a switch in your 
head that you don't put pieces of code that should be protected 
from each other in the same file. Just like you wouldn't put them 
in the same class in your current mindset. It's not all that 
different.

There are advantages and disadvantages to each approach. D's 
approach makes sense: Why would you trust someone with access to 
a file not to change the classes in that file, like slip a friend 
in there for convenience? These things are much easier to catch 
in review if spread over different files. The off-limits file can 
even be write protected in the RCS. You don't even need to see 
that file, just the generated documentation of it.

(Did you watch the video?)


More information about the Digitalmars-d mailing list