Tango Style: Struct with no members?

Bill Baxter wbaxter at gmail.com
Sat Sep 6 15:18:15 PDT 2008


On Sun, Sep 7, 2008 at 6:58 AM, Benji Smith <dlanguage at benjismith.net> wrote:
> I've been reading a lot of the Tango source code lately, to educate myself
> on how the library works, and more generally, how to write good idiomatic D
> code.
>
> As I've looked around, I've noticed a peculiar idiom popping up again and
> again that I've never seen or heard of before: struct definitions with no
> member fields, only functions. You can see it in "tango.time.WallClock" or
> "lib.common.tango.core.Runtime".
>
> What's the rationale behind that?
>
> I suppose it's something like a class with nothing but static methods. But
> then why not just define a module with only free functions? Is there a
> hidden benefit to implementing a pseudo-module as an empty struct?

It prevents namespace pollution.  In general you don't want to have a
bunch of generically named functions like "getTime" floating around in
the top level namespace.  A user *can* do static or renamed import to
prevent this, but since those are not the default, most users don't do
that. In C++ you'd do the same thing with an explicit namespace, but D
doesn't have a namespace construct separate from module namespaces.
You have to use a struct or template to get that sort of effect.

--bb


More information about the Digitalmars-d-learn mailing list