What exactly module in D means?

Philippe Sigaud via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 6 01:55:45 PDT 2014


On Sat, Jul 5, 2014 at 6:35 PM, Andre Tampubolon via
Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
> I've been reading the newsgroup for a while, and it seems that one of the
> reason folks like D is because it supports module.
>
> My question is: what does module mean?
> A quick google pointed my this page: http://dlang.org/module.html.
> Still cannot understand it, though :)
>
> How does it differ from the old C's #include?

Well, module are 'more first-class' in D than in C. By this, I mean
that they have an identity: a name, members, symbols. You can see them
as a enormous struct/class. You can use introspection to obtain the
symbols defined in a module, query their types, etc. Heck, in some
cases, module names can even by used as arguments for templates.

As others said, a D module is a unit of encapsulation: inside a
module, functions, structs and classes can freely call one other and
access their internal fields. Outside the module, only what's not
private is visible. Thus, you can create complex, interdependent
structures inside your module, but export only some parts for public
access. This way, you control a module 'interface', its external
frontier.

Importing a module in D means the public symbols defined in the module
become accessible in the importer. There is no need to import all
visible symbols in your current scope: you can restrict your import to
only one or two symbols, rename them, etc. That's much more powerful
than C when it comes to name clashes.

Different 'downstream' modules can import the same 'upstream' module,
and choose to import different symbols. No need to do a big 'import
everything in the current scope'.

symbols names are also defined on a per-module basis: two different
modules can have members with a similar name, without clash: just
prefix the names with the module name to differentiate them (or rename
one while importing).

Also, `import foo;` is a statement, you can put it everywhere a
statement is legit. That's a recent addition (ie, 1-2 year?), that
Andrei likes to call 'Turtles all the way down' and is quickly
becoming a D idiom: import a symbol near its use place: inside a
function, a method, even inside an if branch: that avoid scope
pollution and nicely documents where a symbol is necessary.


More information about the Digitalmars-d-learn mailing list