Inner modules / namespaces

Bill Baxter dnewsgroup at billbaxter.com
Sat Sep 15 18:46:01 PDT 2007


One thing I find I keep wishing D had was a way to make a distinct 
namespace inside a file.  This would make it possible to group bits of 
functionality into namespaces without having to break each one out into 
a separate file.

I think the most natural way to do this would be to allow inner modules. 
  These modules would not be directly importable from outside but would 
be accessible from outside if public.

Basic example:

------
private module Detail {
    import std.stdio;
    import std.string;
    import std.regex;
}
...
Detail.writefln("hi there");
------

This would basically be equivalent to making a separate file called 
"Detail.d" whose contents are

    public import std.stdio;
    public import std.string;
    public import std.regex;

And then doing

    static import Detail;

In the original module.  Except you don't have to actually go through 
the rigmarole of making a separate file.  *ALSO* Detail and the main 
module would have same-module access to each others privates.

The mutual access is the big thing.  You can make separate modules now, 
but that's not so useful for implementing a private "Detail" namespace 
that hides a bunch of non-public functionality behind one name.  Yes, 
you can achieve similar results with a big private {...} block but the 
difference is that you can't give that private block a name.  By putting 
your private stuff in one namespace, it becomes easier for readers of 
the code to figure out what's private functionality and what's not.

The other advantage is that it makes it easier to aggregate several 
modules under a common namespace within a module.  For instance I often 
wish I could do something like

private module Util {
    import std.string;
    import my.utils;
    import your.utils;
}

and get at all those Util things via one Util prefix.  Yes I can do that 
by creating another module with public imports, but I never do, because 
its a pain, and this particular combination of Util modules is probably 
never going to be used anywhere besides this one module.  So it doesn't 
really make sense to create a world-visible module that's basically 
useless aside from inside this one module.

I'm planning to throw this up as an enhancement request on Bugzilla, but 
I thought I'd put it out here first to see what the reaction is.

--bb



More information about the Digitalmars-d mailing list