views:

475

answers:

4

I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?

For example, I have a type that I need to use all over a particular application - should I define it thus:

mytypes.h

typedef int MY_TYPE;

foo.cpp

MY_TYPE myType;

Or use a namespace:

mytypes.h

namespace ns {
typedef int MY_TYPE;
}

foo.cpp

ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;

Which do you prefer? Are there times when it is acceptable to use the first method?

+2  A: 

I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project.

The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application.

So, if your MY_TYPE is used throughout your application, put it in the global namespace, otherwise put it in a named namespace.

Anthony Williams
I mostly agree, but if MY_TYPE is used throughout an application I would consider it a possible sign of that it might serve better as part of a separate module/library.
Andreas Magnusson
+3  A: 

I don't agree with using the global namespace at all (well, except for main, of course). For things that are used across the whole application, you can simply use using namespace at the top of your .cpp files, after all the relevant #include lines.

Chris Jester-Young
Let's not go to the extremes: from not using namespaces at all to not using global namespace IMHO. A global namespace is exactly that - a namespace. Something like CObject for MFC classes ;) It also can be useful.
Marcin Gil
I suppose I come from the Java school of thought, which says that everything should be in a package (unless you're writing a trivial application, I suppose). In Java, classes in the unnamed package have second-class status compared to classes in a named package.
Chris Jester-Young
+7  A: 

You can define your type in a separate namespace, and use

using ns::MY_TYPE;
Igor Semenov
+1  A: 

Libraries must not, Applications may.

When multiple people work on an application, of course you need clear rules, and the clearest rule is "don't". However, this isn't ideal in all cases.

"using" statements should go only on top of CPP files, never in headers - but that complicates writing templates since - for most compilers in the near future - they need to reside in headers.

In my experience (mostly small team with a large but well-partioned project), namespace pollution isn't much of a problem as long a you controll the respective code, and insist on descriptive names. The cases I remember were few and far between and easily dealt with. There were major problems with 3rd party libraries, though - even with source available.

YMMV with a huge team or a huge project that goes into a single compile.

peterchen