Why do private member variables behaved like protected in the same module when creating deriving class?
Mike Parker
aldacron at gmail.com
Mon Oct 29 06:15:25 UTC 2018
On Monday, 29 October 2018 at 05:13:22 UTC, unprotected-entity
wrote:
>
> Having said that, I am yet to hear a really good argument, as
> for why everything in a module *must* be your friends.
> Encapsulation, is not about having lots of friends that can
> poke at your private parts - no matter what language it is.
>
I've always understood encapsulation to be about the public API.
I've generally seen two primary reasons given as to the purpose
behind managing access: hiding complexity, and managing change.
For the first, consumers of an API need not know or care about
the implementation details. Access modifiers allow the producers
of an API to hide the details of the implementation and only
expose what the consumer actually needs.
For the second, changes to the implementation of an API should
ideally not impact the public API. Access modifiers allow the
producer to segregate the changeable from the unchangeable.
From that perspective, D's system does not break encapsulation.
From outside the module, publicly accessible symbols (including
classes, structs, their members, and module-scope declarations)
provide the public API for which change should be minimal. From
inside the module, encapsulation is achieved with the package and
private access modifiers.
In my opinion, you're making a purely abstract argument.
Conceptually, the class is its own entity, true. But anyone who
can edit the file in which the class resides can also edit the
class implementation. Encapsulation inside the file is rather
pointless.
I understand the argument about accidentally bypassing accessors
to directly modify private members that shouldn't be modified.
But the same thing can happen from inside the class. IIRC, one of
the tips in Effective Java was to always use accessors to modify
member variables even inside the class, and it's fairly common in
Java to do so, to avoid causing subtle bugs like that. But the
language doesn't require it, nor should it.
I see D's modules in the same light. There's no need to add more
complexity to the language to solve a problem that is arguably
rare in practice. If you're worried about accessing private
members in a module, then use a naming convention that clearly
marks private variables (I use an underscore in front, _foo) and
never directly modify any variable with an underscore. If you're
worried about other people doing it, split your modules and use
the package access modifier to organize your package. The tools
to solve this potential issue are there. We don't need more.
Anyway, I'm not the one who needs convincing. And I have a high
degree of confidence that the ones who do need convincing won't
be. There has yet to be a strong enough argument to change this
behavior.
More information about the Digitalmars-d
mailing list