views:

434

answers:

8

I understand that a C++ library should use a namespace to avoid name collisions, but since I already have to:

  1. #include the correct header (or forward declare the classes I intend to use)
  2. 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?

+6  A: 

(a) interfaces/classes/functions from the library

Not any more than you already have. Using namespace-ed library components helps you from namespace pollution.

(b) implementation details inferred by the namespace?

Why? All you should be including is a header useful.h. The implementation should be hidden (and reside in the useful.cpp and probably in a dynamic library form).

You can selectively include only those classes that you need from useful.h by having using useful::Useful declarations.

dirkgently
A: 

If you have multiple implementations of your "useful" library, then isn't it equally probable (if not under your control) that they would use the same namespace, whether it be the global namespace or the useful namespace?

Put another way, using a named namespace versus the global namespace has nothing to do with how "coupled" you are to a library/implementation.

Any coherent library evolution strategy should maintain the same namespace for the API. The implementation could utilize different namespaces hidden from you, and these could change in different implementations. Not sure if this is what you mean by "implementation details inferred by the namespace."

A: 

no you are not increasing the coupling. As others have said - I dont see how the namespace use leaks the implementation out

the consumer can choose to do

 using useful;
 using useful::Foo;
 useful::Foo = new useful::Foo();

my vote is always for the last one - its the least polluting

THe first one should be strongly discouraged (by firing squad)

pm100
Presumably for the first one you intended `using namespace useful;`?
Jerry Coffin
+8  A: 

The namespace has nothing to do with coupling. The same coupling exists whether you call it useful::UsefulClass or just UsefulClass. Now the fact that you needed to do all that work refactoring only tells you to what extent your code does depend on your library.

To ease the forwarding you could have written a forward header (there are a couple in the STL, you can surely find it in libraries) like usefulfwd.h that only forward defined the library interface (or implementing classes or whatever you need). But this has nothing to do with coupling.

Still, coupling and namespaces are just unrelated. A rose would smell as sweet by any other name, and your classes are as coupled in any other namespace.

David Rodríguez - dribeas
"Now the fact that you needed to do all that work refactoring only tells you to what extent your code does depend on your library." That's a really good point. I made the code into a library so others could make use of it, but my original code was heavily dependent on that functionality.
Kassini
+1 for the correct answer.
John Dibling
+9  A: 

It sounds to me like your problem is due primarily to how you're (ab)using namespaces, not due to the namespaces themselves.

  1. It sounds like you're throwing a lot of minimally related "stuff" into one namespace, mostly (when you get down to it) because they happen to have been developed by the same person. At least IMO, a namespace should reflect logical organization of the code, not just the accident that a bunch of utilities happened to be written by the same person.

  2. A namespace name should usually be fairly long and descriptive to prevent any more than the most remote possibility of a collision. For example, I usually include my name, date written, and a short description of the functionality of the namespace.

  3. Most client code doesn't need to (and often shouldn't) use the real name of the namespace directly. Instead, it should define a namespace alias, and only the alias name should be used in most code.

Putting points two and three together, we can end up with code something like this:

#include "jdate.h"

namespace dt = Jerry_Coffin_Julian_Date_Dec_21_1999;

int main() {

    dt::Date date;

    std::cout << "Please enter a date: " << std::flush;
    std::cin>>date;

    dt::Julian jdate(date);
    std::cout   << date << " is " 
                << jdate << " days after " 
                << dt::Julian::base_date()
                << std::endl;
    return 0;
}

This removes (or at least drastically reduces) coupling between the client code and a particular implementation of the date/time classes. For example, if I wanted to re-implement the same date/time classes, I could put them in a different namespace, and switch between one and the other just by changing the alias and re-compiling.

In fact, I've used this at times as a kind of compile-time polymorphism mechanism. For one example, I've written a couple versions of a small "display" class, one that displays output in a Windows list-box, and another that displays output via iostreams. The code then uses an alias something like:

#ifdef WINDOWED
namespace display = Windowed_Display
#else
namespace display = Console_Display
#endif

The rest of the code just uses display::whatever, so as long as both namespaces implement the entire interface, I can use either one, without changing the rest of the code at all, and without any runtime overhead from using a pointer/reference to a base class with virtual functions for the implementations.

Jerry Coffin
*"as a kind of run-time polymorphism mechanism"* - that should be *"compile-time"*?
Georg Fritzsche
@gf:oops, yes. Thanks. I'll fix that.
Jerry Coffin
+1 Great suggestion.
Kassini
God, I definitely don't name my namespaces with my surname and date... we have a few hundreds of components at work, and the name is usually the name of the component, to differentiate them :)
Matthieu M.
@Matthieu:the point is simply to come up with a pattern you can follow that gives a reasonable assurance that it's unique. The whole point of what I'm advocating is that about the only time you use that name directly is as the target of an alias.
Jerry Coffin
I understand, but each of your client needs to either wrap your headers with the alias or redefine the alias at each inclusion, that's a bother. Furthermore, as a naming convention, I use the namespace as the path to my file >> `#include "name1/name2/class.h"` means `name1::name2::Class`, which makes it easy to identify at a glance to which module (submodule...) a class belongs and which header bring it in.
Matthieu M.
A: 

Well, the truth is there's no way to easily avoid entanglement of code in C++. Using global namespace is the worst idea, though, because then you have no way to pick between implementations. You wind up with Object instead of Object. This works ok in house because you can edit the source as you go but if someone ships code like that to a customer they should not expect them to be for long.

Once you use the using statement you may as well be in global, but it can be nice in cpp files to use it. So I'd say you should have everything in a namespace, but for inhouse it should all be the same namespace. That way other people can use your code still without a disaster.

Charles Eli Cheese
+2  A: 

I'd like to expand on the second paragraph of David Rodríguez - dribeas' answer (upvoted):

To ease the forwarding you could have written a forward header (there are a couple in the STL, you can surely find it in libraries) like usefulfwd.h that only forward defined the library interface (or implementing classes or whatever you need). But this has nothing to do with coupling.

I think this points to the core of your problem. Namespaces are a red herring here, you were bitten by underestimating the need to contain syntactic dependencies.

I can understand your "laziness": it is not right to overengineer (enterprise HelloWorld.java), but if you keep your code low-profile in the beginning (which is not necessarily wrong) and the code proves successful, the success will drag it above its league. the trick is to sense the right moment to switch to (or employ from the first moment the need appears) a technique that scratches your itch in a forward compatible way.

Sparkling forward declarations over a project is just begging for a second and subsequent rounds. You don't really need to be a C++ programmer to have read the advice "don't forward-declare standard streams, use <iosfwd> instead" (though it's been a few years when this was relevant; 1999? VC6 era, definitely). You can hear a lot of painful shrieks from programmers who didn't heed the advice if you pause a little.

I can understand the urge to keep it low-brow, but you must admit that #include <usefulfwd.h> is no more pain than class Useful, and scales. Just this simple delegation would spare you N-1 changes from class Useful to class useful::Useful.

Of course, it wouldn't help you with all the uses in the client code. Easy help: in fact, if you use a library in a large application, you should wrap the forward headers supplied with the library in application-specific headers. Importance of this grows with the scope of the dependency and the volatility of the library.

src/libuseful/usefulfwd.h

#ifndef GUARD
#define GUARD
namespace useful {
    class Useful;
} // namespace useful
#endif

src/myapp/myapp-usefulfwd.h

#ifndef GUARD
#define GUARD
#include <usefulfwd.h>
using useful::Useful;
#endif

Basically, it's a matter of keeping the code DRY. You might not like catchy TLAs, but this one describes a truly core programming principle.

just somebody
A: 

I would suggest you consider a method of versioning in your code.

I don't know how I'd do that ATM.

Paul Nathan