Are modules analogous to namespaces in C# or packages in Java?

Mike Parker aldacron at gmail.com
Thu Jan 2 00:24:01 PST 2014


On 1/2/2014 2:43 AM, Afshin wrote:
> Modules confuse me as a way to organize code.
>
> If a module is composed of multiple classes, it seems that the module
> semantics in D encourages putting all those classes in one file.
>
> Can someone explain how to organize a set of classes into a module (or
> namespace, or package) so that each class can have their own file?

Just think of a module as a source file, much like a Java source file. 
You can think of foo.d as being the same as foo.java.

Modules (D source files) can be organized into packages, very much like 
Java source files can. So if you have a file bar/baz/foo.d, you can add 
this at the top:

module bar.baz.foo;

This means package bar contains a subpackage baz which contains a module 
foo.

You can organize your modules any way you'd like, so if you want to put 
one class in each module, that's perfectly fine:

==============
// bar/baz/foo.d
module bar.baz.foo;

class Foo {}

// bar/baz/borg.d
module bar.baz.borg;

class Borg {}

==============

Unlike Java source files, D source files (modules) allow you to place 
variable declarations and free functions at module-scope. They can be 
public, package, or private, just like class members and methods.

==============
module bar.baz.foo;

interface Foo {}

private fooCount;

Foo makeFoo( int someFlag;) {
     ++fooCount;
     if( someFlag ) return new FooImpl1;
     else return new FooImpl2;
}

private class FooImpl1 : Foo {}

private class FooImpl2 : Foo {}
==============

In D, private class methods and variables are visible inside the module 
in which they are declared. This can be very handy. For example, if 
FooImpl1 and FooImpl2 have private methods, other functions and class 
mehtods in bar.baz.foo can call them directly. This is one of the 
reasons I prefer in my own code not to use one class per module. I group 
modules based on related functionality. I may have a variety of free 
functions, classes, structs, enums, and private variables in a single 
module. But I do try to keep each module to a reasonable size. I don't 
like seeing thousands of lines in a single module. Choosing the 
granularity for separating functionality into separate modules is just a 
matter of taste.

Ultimately, D gives you a lot of freedom in how to organize your module 
layout.


More information about the Digitalmars-d-learn mailing list