On Friday, 13 January 2023 at 05:17:59 UTC, thebluepandabear
wrote:
(Sorry if this is a duplicate.)
If I have the following code inside of a module:
```D
class Obj {
private {
string name = "Hi";
}
}
class ObjDerived : Obj {
}
```
Is it best practice to define `ObjDerived` inside another
module, since `ObjDerived` can still access the members of
`Obj` (since `private` is only applied to modules), or does
this go against the intended use of the language?
As a beginner, I am having an extremely tough time
understanding why you would want to place these two classes in
the same module or even have this intended behavior of
`private`. I am coming from Java/Kotlin which are both strictly
OO language and have different ways of encapsulation.
The short answer: just think of a module as a way of grouping
related objects and functions. If it makes sense to you for
`ObjDerived` to have access to the internals of `Obj`, then keep
them in the same module. If it doesn't, then put it somewhere
else.
The long answer: there's no one-size-fits all here. For a short
program, a script let's say, just dump everything in one module
and be done with it. For a program you're writing for your own
use, do whatever you feel comfortable with, even if you plan to
open source it.
For something you're writing for others to use, like a library,
then the first priority is to think about what the public facing
API should look like. From that perspective, does `ObDerived`
belong in the same module, or is it unrelated enough to go into a
different one?
If it does fit in the same module, then that can be enough. It is
for me. I'd stop there. But some people want to go one step
further and ensure that `ObjDerived` can't access the internals
of `Obj`. So in that case, you can put them in two separate
modules and make a `package.d` file to act as the common module
name for both. I think there are good reasons to do that, but
most of the time it's just a matter of preference.