Would it be considered bad practice to use sub-namespaces for purely organizational purposes? For example:
namespace vehicles
{
namespace cars
{
// Stuff here
}
namespace boats
{
// More stuff here
}
}
I can see how this would be a problem on large projects, because it would be inconvenient to type vehicles::cars::function a lot. What about small projects, though?
Why would it be less inconvenient to type
vehicles::cars::functiona lot in a small project?Remember what purpose namespaces are supposed to serve. They are supposed to avoid name clashes, and not much else.
If you invent such a convoluted namespace structure that I’m tempted to just put a few
using namespace ...‘s at the top of every file, then it defeats the purpose of namespaces.It also doesn’t really tell me much I didn’t know already. What are you going to put in your
boatsnamespace that I wouldn’t know from the name alone was a boat? Am I going to need the clarification that “this belongs with the boats” on anything in the namespace? Most likely not, and then there’s no point in having the namespace.In general, don’t ask what problems there are with using any language feature until you’ve found out what the advantages are. Every feature needs to justify itself. So what problem would your proposed namespaces solve?
If it wouldn’t solve a real, actual problem, then it is a bad idea, regardless of anything else.
I always think it’s instructive to look at different language’s standard libraries.
.NET uses deeply nested namespaces with long names. The full name for a simple dynamic array is
System.Collections.Generic.List<T>.As a result, no-one ever uses the namespace. Everyone just puts a
using System.Collections.Genericat the top of every file that needs to use a List.And because of this, you’re in trouble the moment you encounter another
Listclass. You’ll want to do the same with that, and voila, you have twoListclasses clashing.C++ uses a very flat namespcae structure, where namespaces also have very short names.
The equivalent class in C++ is simply
std::vector. As a result, people generally type out the namespace prefix, and so, when I add another vector class to my project, *it works’. There are no name clashes, because I use thestd::prefix when I want to refer to the standard library vector.