tags:

views:

155

answers:

1

I am interested in unprecedented, cool, and esoteric ways to use namespaces. I know that many advanced developers "hack" namespaces by, for example, using them as references to string constants. In the string constants example, the idea is to implement DRY (DRY = Do Not Repeat Yourself) and you can keep all your strings in one file.

note: I am looking for answers related to "common" languages such as C#, Ruby, Java, etc.

+1  A: 

One esoteric use I often resort to is when defining enums in C++, especially when there are several types in a cetain context. This enables usage such as Quality::k_high and Importance::k_high in related contexts. Enums also often sport unknown values (usually to represent cases where none have been set), which need to be qualified to disambiguate constants (say, k_qualityNone and k_importanceNone), which is avoided using namespaces.

A definition will thus look like:

namespace Quality {
   enum Type { k_high, k_medium, k_low, k_none };
}

and

namespace Importance {
   enum Type { k_high, k_medium, k_low, k_none };
}

Functions and methods will then take an argument of type Quality::Type (and Importance::Type), which is rather descriptive and nice. Individual enumeration constants are also qualified similarly as mentioned earlier (Quality::k_low).

I also use and love this technique because it helps self document the code.
Robert Gould