I understand that a C++ library should use a namespace to avoid name collisions, but since I already have to:
#include
the correct header (or forward declare the classes I intend to use)- Use those classes by name
Don't these two parameters infer the same information conveyed by a namespace. Using a namespace now introduces a third parameter - the fully qualified name. If the implementation of the library changes, there are now three potential things I need to change. Is this not, by definition an increase in coupling between the library code and my code?
For example, look at Xerces-C: It defines a pure-virtual interface called Parser
within the namespace XERCES_CPP_NAMESPACE
. I can make use of the Parser
interface in my code by including the appropriate header file and then either importing the namespace using namespace XERCES_CPP_NAMESPACE
or prefacing declarations/definitions with XERCES_CPP_NAMESPACE::
.
As the code evolves, perhaps there is a need to drop Xerces in favour of a different parser. I'm partially "protected" from the change in the library implementation by the pure-virtual interface (even more so if I use a factory to construct my Parser), but as soon as I switch from Xerces to something else, I need to comb through my code and change all my using namespace XERCES_CPP_NAMESPACE
and XERCES_CPP_NAMESPACE::Parser
code.
I ran into this recently when I refactored an existing C++ project to split-out some existing useful functionality into a library:
foo.h
class Useful; // Forward Declaration
class Foo
{
public:
Foo(const Useful& u);
...snip...
}
foo.cpp
#include "foo.h"
#include "useful.h" // Useful Library
Foo::Foo(const Useful& u)
{
... snip ...
}
Largely out of ignorance (and partially out of laziness) at the time, the all of the functionality of useful.lib
was placed in the global namespace.
As the contents of useful.lib
grew (and more clients started to use the functionality), it was decided to move all the code from useful.lib
into its own namespace called "useful"
.
The client .cpp
files were easy to fix, just add a using namespace useful
;
foo.cpp
#include "foo.h"
#include "useful.h" // Useful Library
using namespace useful;
Foo::Foo(const Useful& u)
{
... snip ...
}
But the .h
files were really labour intensive. Instead of polluting the global namespace by putting using namespace useful;
in the header files, I wrapped the existing forward declarations in the namespace:
foo.h
namespace useful {
class Useful; // Forward Declaration
}
class Foo
{
public:
Foo(const useful::Useful& u);
...snip...
}
There were dozens (and dozens) of files and this ended up being a major pain! It should not have been that difficult. Clearly I did something wrong with either the design and/or implementation.
Although I know that library code should be in its own namespace, would it have been advantageous for the library code to remain in the global namespace, and instead try to manage the #includes
?