Module-level privacy

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun May 13 18:01:41 UTC 2018


On Sunday, May 13, 2018 17:19:26 rumbu via Digitalmars-d wrote:
> On Sunday, 13 May 2018 at 15:13:59 UTC, meppl wrote:
> > Also, someone may say: I can see what happens in one and the
> > same file. If there are two classes/structs in one file, they
> > are "friends" and I dont need the "friend"-keyword anymore.
> > Thats an argument, too.
>
> So, when you have 1000 classes, you just create 1000 files just
> to "unfriend" them :)

Which is basically what you get in Java, though no one should be putting
1000 classes in a single module anyway. But if you want to make it so that
classes can't access each other's members while still making it possible to
import them together, then all you have to do is have a module which
publicly imports all of those other modules which have one class each.

The only thing that you really lose with D's approach as opposed to friend
is that D doesn't provide a way to mark something from another module as a
friend. package at least partially solves that problem though. Really, what
D went with is similar to what Java did, only it's more flexible, because it
doesn't restrict what can go in a module, whereas Java only allows one
public class per module and doesn't have any free functions.

Ultimately, D's solution simplifies things over what C++ did with friends
while giving you basically the same level of control. It's just that if you
don't want something to be able to access the private members of a class or
struct, that symbol must be in a separate module. So, if you _really_ don't
want anything accessing the internals of your class or struct, but you want
to be able to stick stuff in the same file, then that can get annoying,
because you can't do that. But public imports let you make it so that you
can still import them as one even if they're not actually in the same file,
and many of us have found that having the default be that other stuff in the
module can access the private members to be very useful - especially with
regards to testing.

I fully expect that if we added some sort of "super private" that really
made it so that nothing outside a class or struct could access its members,
almost no one would use it, and it wouldn't really solve much in the way of
real problems, much as I'm sure that a few folks like KingJoffrey would be
quite happy to have something like that.

Ultimately, there are tradeoffs between what C++ did and what D did, and
neither approach is perfect, so some folks are likely to be happier with one
approach over the other, but overall, what D has done has worked extremely
well for D.

- Jonathan M Davis



More information about the Digitalmars-d mailing list