When using nested namespaces sometimes fully qualified names end up being quite long. I know I can use namespace abc = aaa::bbb::ccc for reducing the amount of typing (it may also improve readability in some cases).
I am not sure, however, what is the best way to achieve this renaming across all the files in a project. The straightforward approach (i.e., to rename long namespaces in a per-use basis) might lead to end up using different short names for the same fully qualified name in different files. So, I was thinking to come up with a more consistent way to do this.
For instance, let's assume something like:
project
|- client
| |- core
| |- plugin
| |- util
|- server
...
I was thinking to create one header per directory including the reduced names. For instance, project/client/core/core.h would contain namespace pr_cl_core = project::client::core (I know the example for this short name is rather poor, but in real projects they make more sense). Then, I would include core.h into all the header files in project/client/core so that when a header from that directory is included in, let's say, project/client/plugin/plugin_foo.h, the short namespace versions are readily available.
Is this a good approach to do so? Is there any other better way?
I have found several questions on C++ namespaces on SO (for instance, 1 and 2), but none of them relates to how to solve namespace renaming in a project-wide manner.
EDIT: Additionally, such a mechanism could be used to systematically rename long namespaces (such as Boost's ones) for a whole project. For instance, I typically rename some namespaces like:
namespace ip = boost::asio::ip;
namespace ptime = boost::posix_time;
Currently I do this on a per translation-unit basis, but I would like to do it using a global approach for the whole project.
I would argue that if you repeatedly have to type long namespace names, then something is wrong in your namespace hierarchy.
Suppose you would have the same with classes, repeatedly finding yourself typing obj->sub()->subsub()->some_method(). This would be a violation of the Law of Demeter. In the case of classes, you would refactor your code (by writing wrapper functions) so that classes down in the hierarchy only have to access methods one level up.
The same should be done with namespaces: if you have to call project::client::core then you should write wrapper functions/classes in client to expose the necessary interfaces to project. If you need to do this all over the place, why not flatten your namespace structure so that client and core are at the same level?
The fact that Boost uses nested namespace is only partly true, because most of the nested namespaces like aux and detail are not supposed to be called by clients. E.g. Boost.MPL is a really good example of a library that is careful not to gratuitously expose nested namespaces.
Related
I am a C++ newcomer, trying to learn the language in parallel as I work on a project that requires it. I am using a fairly popular and stable open source library to do a lot of heavy lifting. Reading through the source, tutorials and code samples for the library, I have noticed that they always use fully qualified names when declaring types, which often results in very long and verbose lines with lots of ::'s. Is this considered best practice in C++? Is there a different way to deal with this?
They may have found it easier than answering lots of questions from people who tried the example code and found it didn't work, just because they didn't "use" the namespaces involved.
Practices vary - if you're working on a large project with lots of diverse libraries and name clashes, you may wish to proactively use more namespace qualifiers consistently so that as you add new code you won't have to go and make old code more explicit about what it's trying to use.
Stylistically, some people prefer knowing exactly what's being referred to to potentially having to dig around or follow an IDE "go to declaration" feature (if available), while other people like concision and to see fuller namespace qualification only on the "exceptional" references to namespaces that haven't been included - a more contextual perspective.
It's also normal to avoid having "using namespace xxx;" in a header file, as client code including that header won't be able to turn it off, and the contents of that namespace will be permanently dumped into their default "search space". So, if you're looking at code in a header that's one reason they might be more explicit. Contrasting with that, you can having "using namespace" inside a scope such as a function body - even in a header - and it won't affect other code. It's more normal to use an namespace from within an implementation file that you expect to be the final file in a translation unit, compiling up to a library or object that you'll link into the final executable, or perhaps a translation unit that itself creates the executable.
First typedefs:
typedef std::vector<MyTypeWithLongName>::const_iterator MyTypeIt;
//use MyTypeIt from now on
Second "using"
using std::string;
//use string instead of std::string from now on
Third "using namespace"
using namespace std;
//Use all things from std-namespace without std:: in front (string, vector, sort etc.)
For the best practice: Don't use 'using' and 'using namespace' a lot. When you have to use it (sometimes keeps the code cleaner) never put it in the header but in the .cpp file.
I tend to use one of those above if the names get really long or I have to use the types a lot in the same file.
If you are writing your own libraries you will certainly have heavy use of namespaces, In your core application there should be fewer uses. As for doing something like std::string instead of starting with using namespace std; imo the first version is better because It is more descriptive and less prone to errors
I am building a library that consists of many different classes and files but they are all related so I am thinking that putting them in the same namespace is a good idea; this also allows me to use less risky generic/simple class names since name collision inside the namespace is not an issue.
Is the process of using the same namespace for many different files as simple as simply putting all the classes inside the same-named namespace?
ClassA.h, ClassB.h, ClassC.h, etc contain this:
namespace Whatever{
...Class definition
}
Yes you can surely move ahead with this idea. If we use same namespace name in different files those get automatically clubbed into one.
As per the comment by Joachim Pileborg, this is acceptable organizational style, and is in fact used by the STL itself.
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?
It sounds to me like your problem is due primarily to how you're (ab)using namespaces, not due to the namespaces themselves.
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.
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.
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.
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.
(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.
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.
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."
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)
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.
I come from a c# background where everything has its own namespace, but this practice appears to be uncommon in the c++ world. Should I wrap my code in it's own namespace, the unnamed namespace, or no namespace?
Many C++ developers do not use namespaces, sadly. When I started with C++, I didn't use them for a long time, until I came to the conclusion that I can do better using namespaces.
Many libraries work around namespaces by putting prefixes before names. For example, wxWidgets puts the characters "wx" before everything. Qt puts "Q" before everything. It's nothing really wrong with that, but it requires you to type that prefix all over again, even though when it can be deduced from the context which declarations you mean. Namespaces have a hierarchic order. Names that are lexically closer to the point that reference them are found earlier. So if you reference "Window" within your GUI framework, it will find "my::gui::Window", instead of "::Window".
Namespaces enable some nice features that can't be used without them. For example, if you put your class into a namespace, you can define free functions within that namespace. You then call the function without putting the namespace in front by importing all names, or selectively only some of them into the current scope ("using declaration").
Nowadays, I don't do any project anymore without using them. They make it so easy not to type the same prefix all over again, but still have good organization and avoidance of name-pollution of the global namespace.
Depends, if your code is library code, please wrap it in namespaces, that is the practice in C++. If your code is only a very simple application that doesn't interact with anything else, like a hello world sort of app, there is no need for namespaces, because its redundant.
And since namespaces aren't required the code snippets and examples on the web rarely use them but most real projects do use them.
I just discovered Google's c++ style guide and they have namespace guidelines.
The whole guide is worth reading, but to summarize, they say:
Add unnamed namespaces to .cc files, but not .h files.
Wrap entire (after includes/declarations) .cc and .h files in named namespaces.
Namespaces do not increment the indent level.
At the closing brace for a namespace write } // namespace.
Don't declare anything in std, because it is undefined.
using the using directive is forbidden.
the using declaration is allowed in functions, methods, and classes.
namespace aliases are allowed anywhere.
It really depends upon whether you expect there to be any conflicts.
Two scenarios;
1) If you are creating code that may be used by others (e.g libraries) then there could be namespace clashes so using your own namespace is a good idea.
2) If you are using third-party libraries their code may not be namespaced and could conflict with yours.
I would also say that if you expect your code to be sizable and cover many different areas (math/physics/rendering) then using namespaces does make the code easier to grok, particularly for types that are not obviously classified.
We had problems wrapping code in managed C++ that uses our common libraries here.
Some classes had the same names as System class in the .NET library (i.e. System.Console).
We had to do some ugly macro patches to workaround these problems.
Using namespaces at the beginning would have prevented this.
You only really need namespaces if there's a risk of names conflict - some globally seen function or variable or class is defined more than once. Otherwise you'll do just fine with no namespace - just name your classes so that they don't duplicate runtime library classes and make global functions/variable to be static members of some reasonable classes.
I'd say that it's a good idea, if for no other reason than to keep your stuff from getting stepped on when mixed with other third-party code.
I try to go even farther than that by putting as many variables and functions as I can into classes. But that's sometimes harder to do than it should be (compared to other OO languages).
but this practice appears to be
uncommon in the c++ world
Really. All the code I see seems to be wrapped in a namespace.
I use the same type of convention I see in Java (except I drop the com).
In Java
package com.<Company>.<Product>.<Package>;
In C++
namespace <Company>
{
namespace <Product>
{
namespace <Package>
{
}
}
}
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?
You can define your type in a separate namespace, and use
using ns::MY_TYPE;
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.
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.