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.
Related
I would like to evaluate an algorithm with an available public code in my project. I have integrated the files the algorithm needs into my project: kodtree.h, kodtree.cpp, pinpolyhedron.h, and pinpolyhedron.cpp. However, the compiler complains about the ambiguous symbols. I changed the variable names which were ambiguous to something else and the compiler compiles it with no problem. This way does not look like an elegant way of fixing the issue.
I was thinking of using namespace but found out that, for example, the file kodtree.h has several externs.
Would putting them into namespaces cause me trouble since they can contain extern?
Could someone kindly let me know the things I should be aware of when creating namespaces for such libraries?
Is using namespace the right way of doing this?
Or is it better to create an interface class for this library and put everything, i.e., kodtree.h, kodtree.cpp, pinpolyhedron.h, and pinpolyhedron.cpp, inside that class and make them private?
What is the recommended way of doing this?
I would appreciate any tips.
Is using namespace the right way of doing this?
Yes, but not the way you try to go about it. Libraries should properly namespace themselves, but sometimes they can't or won't for various reasons. It's best to leave them be, unless you intend to write a full blown wrapper around the library code.
We can always apply a little discipline and namespace our own code. Simply put, we can do something like this in every one of our own source files1:
#include <some_library.h>
#include <my_other_project_header.h>
namespace ProjectName { namespace ModuleName {
// Your code here
}}
That way your code is nicely insulated from whatever you include. And barring any extern "C" things, there should be no conflicts. Whatever the library header drags in, it will not cause clashes with code you write inside your namespaces. All the while, your code can refer to project entities with at most one level of qualification (code in Module1 can refer to Module2::Foo, or to Module1::Bar as simply Bar). Beyond that you can always refer to things outside your Project namespace by fully qualifying things or by employing using declarations.
1: If your compiler supports C++17, it can be the more palatable:
namespace ProjectName::ModuleName {
}
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 am using two large libraries (GUI & network) and I can happily do
using namespace FirstLib;
using namespace SecondLib;
Except for 1 single class called Foobar where names clash.
I my code, I do not use FirstLib::Foobar. Is there a way to say "in my code, whenever you see Foobar, think SecondLib::Foobar ?
using namespace is evil! Namespaces were made to prevent such problems as you have! But that said, try:
using namespace FirstLib;
using namespace SecondLib;
using SecondLib::Foobar;
or even (for some compilers):
using namespace FirstLib;
using namespace SecondLib;
typedef SecondLib::Foobar Foobar;
It's strange nobody suggested to replace the full namespace use by the list of used class names. This solution is even in the C++faq (where I should have thought to look first).
If we cannot say
include all FirstLib, but remove SecondLib::Foobar
We can use using-declarations of the exact elements we need:
using FirstLib::Boids;
using FirstLib::Life;
// no using FirstLib::Foobar...
You've basically answered your own question. You must explicitly say which class you want to use, so you must do SecondLib::Foobar whenever you use that class.
You have to pick one of these namespaces and get rid of the 'using', and explicitly call out all the class names. C# has a way around this, but C++ does not afaik...
I don't think there's a way of excluding names. You either bring in the whole lot, or each one individually. Even when you bring in the whole lot, you can always disambiguate conflicting names by qualifying them fully.
However, you could use typedef to rename the offending class:
typedef Lib2::FooBar FooBaz;
And I guess, with a conflicting function, you could use a function pointer to "rename" the conflicting one.
I guess it's kind of a non-solution. I can understand the occasional motivation to use using declarations - sometimes there are indeed many different names that you'll use all over the place - but if just one is conflicting: be explicit. It would be confusing to anyone familiar with the libraries anyway, seeing that both namespaces are imported.
Also, using declarations respect scope: you can make one namespace visible in one function, but not the other namespace - assuming you don't even use it in that function.
Have you tried:
using SecondLib::Foobar;
?
If you load all elements from both namespace to current scope by use of using namespace directove:
using namespace FirstLib;
using namespace SecondLib;
and there is potential that some of the names in those namespace may clash, then you need to tell compiler explicitly which of the element you want to use, in current scope, by use of using declaration:
using SecondLib::Foobar;
As the C++ standard says:
7.3.3 The using declaration
1 A using-declaration introduces a
name into the declarative region in
which the using-declaration appears.
That name is a synonym for the name of
some entity declared elsewhere.
This line requests compiler to think SecondLib::Foobar whenever it sees Foobar for the rest of current scope in which the using declaration was used.
The using directive and declaration is very helpful, but they may cause problems as the one you're dealing with. So, it's a good idea to narrow use of any form of using to minimal scope possible. You can use the directive using namespace in scope of other namespace
namespace MyApp {
using namespace ::SecondLib;
}
or even a function. The same applies to using declaration. So, it's a good idea to narrow the scope of use of any of them:
void foo()
{
::SecondLib::Foobar fb;
}
It may seem tedious, but it is only when you type, though you most likely use intellisense-enabled editor, so cost is really small, but benefits are large - no confusions, readable code, no compilation issues.
It's also a very good idea to NOT to use using namespace in header scope. See Header files usage - Best practices - C++
My own tip: do use full qualification whenever you need to use any of these types
I like the concept of C++ namespaces, because they help to keep the source code concise while avoiding name conflicts. In .cpp files this works very well, using the "using namespace" declaration. However, in header files this cannot be used, as it "breaks open" the namespace, meaning that the "using namespace" not only applies within the current header file, but to everything that is compiled thereafter. This partly nullifies the advantage of namespaces. Consider for example a header file in which the classes "ourlib::networking::IpAddress" and "ourlib::filesystem::Path" are frequently used.
Is there a way to limit the effect of the "using namespace"-declaration in header files?
You may put, most of frequently use classes in ::ourlib namespace like
namespace ourlib {
using networking::lpAddress;
}
So, if they unique in the project, most likely you would not have problem. So in, any
place in headers you would be able access lpAddress directly without putting in into
global namespace (I assume all your headers inside namespace ourlib)
No, it can't be done :(
You can just import single classes:
using ourlib::networking::lpAddress;
At least if I remember correctly ;)
This might pollute the global namespace still, though. I tend to just live with the long namespace prefixes in header files. This makes it easier to read the header file for other developers (since you don't have to lookup which class comes from which namespace).
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.