Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

using ns::MY_TYPE;

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top