C++ Namespaces, comparison to Java packages
I've done a bunch of Java coding recently and have got used to very specific package naming systems, with deep nesting e.g. com.company.project.db
. This works fine in Java, AS3/Flex and C#. I've seen the same paradigm applied in C++ too, but I've also heard that it's bad to view C++ namespaces as direct counterparts to Java packages.
Is that true, and why? How are namespaces/packages alike and different? What problems are likely to be seen if you do use deep nested namespaces?
In C++ namespaces are just about partitioning the available names. Java packages are about modules. The naming hierarchy is just one aspect of it.
There's nothing wrong, per-se, with deeply nested namespaces in C++, except that they're not normally necessary as there's no module system behind them, and the extra layers just add noise. It's usually sufficient to have one or two levels of namespace, with the odd extra level for internal details (often just called Details).
There are also extra rules to C++ namespaces that may catch you out if overused - such as argument-dependent-lookup, and the rules around resolving to parent levels. WRT the latter, take:
namespace a{ namespace b{ int x; } }
namespace b{ string x; }
namespace a
{
b::x = 42;
}
Is this legal? Is it obvious what's happening? You need to know the precendence of the namespace resolution to answer those questions.
Java packages are not nested, they're flat. Any apparent nesting is nothing more than a naming convention.
For example, the package com.company.project.db
has no relation whatsoever to com.company.project
or com.company.project.db.x
. Code in com.company.project.db
has no more access to code in com.company.project.db.x
than would code in a.b.c
.