Why doesn't Ruby have the same namespace controvery as C++? - c++

One of the greatest offenses in the C++ community is writing using namespace xyz instead of writing the namespace out everywhere in the code.
Ruby has the functional equivalent of namespaces via modules. All of the proposed issues with using an entire namespace in C++ are perfectly valid for including an entire module in Ruby. But in Ruby it is not condemned to do this.
So why doesn't Ruby have the same namespace controvery as C++? What is the difference between including a module in Ruby and using a namspace in C++?

There is a strong cultural component to this since it is perfectly valid to import an entire namespace... BUT
c++ has Argument Dependent Lookup (ADL) and ruby does not. As a program grows, it becomes more and more likely that an innocent using namespace x will accidentally change the meaning of the entire program, because the compiler happens to find a better match in the x:: namespace for a function that has the same name and similar signature to one in the (for example) y:: namespace.
This is the reason for the caution on this issue.

You generally "include" a module when you are mixing-in a functionality from one module into another. There are some parallels between mix-ins and inheritance where you are "absorbing" the functionality of one module/class into the current module/class. Here's a comparison of the two.
However, if you aren't mixing-in functionality, then you would always use the proper namespace qualifier of the module to access its functions.

You normally don't pull everything via an include at top level (the equivalent of using namespace in C++). you "mix" it in where you need functionality from that specific module.

Related

What does using namespaces offer the programmer over just prefixing the function name?

E.g. SFML::Render() vs SFML_Render()
I've noticed in libraries that offer C and C++ bindings, that often the C++ versions make use of namespaces (SFML, libtcod) and the C bindings do the same thing but just prefix the name with what library they belong to.
Both of them require the programmer to prefix the function, both give context as to where they belong, both of them perform the same function. I'm really confused as to what benefits namespaces offer over function prefixing.
using-declarations
You can write using SFML::Render after which you can simply call the function with Render(), without needing the SFML:: in the front. The using-declaration can also be scoped to a function or class. This is not possible with prefixed names.
using-directives
You can also bring a whole namespace to the current scope with using namespace. Everyone knows what using namespace std does. These can also be scoped.
Namespace aliases
If you have a symbol with a long qualified name e.g. mylib::sublib::foo::bar::x, you can write namespace baz = mylib::sublib::foo::bar and then refer to x with just baz::x. These are scope-specific as well.
Among the C-style prefixed names there's usually nothing that big that would need an alias, and if there were you could just use a macro.
Adding to & removing from a namespace
If you have a file full of functions that need to be placed under a namespace x you can simply add two lines to make it happen: namespace x { and }. Removing from a namespace is equally simple. With prefixed names you have to manually rename each function.
Argument-dependent lookup
You may be able to omit the namespace qualification on a function call if the function lives in the same namespace as some of its arguments. For example, if namespace baz contains both an enum E and a function F that takes it, you can write F(baz::E) instead of baz::F(baz::E). This can be handy if you follow the style that prefers namespaced free functions over methods.
So in conclusion, namespaces are more flexible and offer more possibilities than the prefixed naming style.
SFML_Render is easy to find with fgrep -w SFML_Render, whereas SFML::Render may appear in some source files as just Render if the SFML namespace is implicit.
If you program in C++, there are strong benefits in using the C++ constructs, but you better use a powerful environment such as Eclipse or Visual Studio to help you make sense of all the added complexities.
If you want interoperability with C, you should not use namespaces nor overloading.
they way i see it there are severel uses for namespaces.
some of them:
Name isolation: define a package (a set of classes, functions,
globals, type definitions, etc.) in a namespace to ensure that when
included, these names do not conflict with existing code.
Version control: maintain multiple versions of the code.
and offcourse : A using statement can be used to make names available
without the :: scope operator
Ideally, namespaces should
• Express a logical coherent set of features
• Prevent user access to unrelated features.
• Impose minimal notational burden on users.

Are all using directives viewed the same way as using namespace std?

I've easily gotten myself into the habit of prefixing standard identifiers with std:: instead of sticking in a using namespace std;. However, I've started getting into C# and I've noticed that it's very normal to add in whatever using directives are necessary, i.e., you'd see:
using System;
Console.Write("foo");
instead of:
System.Console.Write("foo");
Apparently, as I found out from a C# question on this topic, that usage comes from the fact that individual system namespaces in C# are much, much smaller than std is in C++, and therefore eliminates the problems associated with name clashes, as there is much less likelihood (and you can just find-replace it with a fully qualified name if a library updates with a name-clash), and eliminates the problems associated with a crapload of Intellisense options appearing, as the namespaces are small enough to handle.
The question, then, is that if these are the standing reasons to make use of using directives in C#, is the same true for C++? Is it generally acceptable to apply this to smaller third-party namespaces, as well as your own smaller namespaces?
Now I realize that this might cause a bit of controversy, I want to take this moment to ask that it doesn't turn into an argument. A good answer should include a basis, i.e., advantages or disadvantages, and how using one way over the other really makes a worthwhile difference.
The reason I ask this is to clear up the issue, and possibly remove the notion that using directives in C++ have to be a bad thing. Sure longer namespace names can be cut down with a namespace alias if necessary, and fully qualified names can still be used if needed, but sometimes a using directive greatly eases accessing some members such as user-defined literal operators, which, to my knowledge, have no form of ADL, meaning that you either have to use a using directive, or call the operator method by the function syntax, defeating the whole purpose of using the operator in the first place.
For example, I had a namespace (that includes a structure representing a keyboard key, along with a literal suffix as a readable alternate means of access:
"caps lock"_key.disable();
The problem here is that unless you have previously inserted using namespace Whatever; or using Whatever::operator"" _key;, the code won't compile, which is bad news for the user.
Using directives have obvious problems when std is involved or when used in such a way in a header that they bring unwanted extras for the user of that header, but is it justified to use them for other namespaces when contained within a smaller scope than whatever includes a header? The keystrokes saved from not having to type each qualifier each time do add up, and with today's Intellisense capabilities, finding out which namespace an unqualified identifier belongs to is as easy as mousing over it.
I think the rules about using declarations in C++ are rather simple:
NEVER write "using namespace anything;" in the global scope of a header, especially one that is likely to be reused by other programs (e.g. when writing a library). It pollutes the global scope of all subsequent headers with the symbols of this namespace, which defeats the entire purpose of namespaces, and can create unforeseen name clashes later on.
In the .cpp files and inner scopes of headers (e.g. inline function scopes), you can be "using" whatever namespaces you want, as it won't affect any other file. Just do whatever is more convenient for you and try to be reasonably consistent within a project.
EDIT: for the _key problem, simply define this operator in its own namespace and tell users to import it. This way they won't need to type out the operator declaration.
namespace something {
class key { ... };
}
namespace key_suffix {
something::key operator"" _key() { ... }
}
// user code
void some_function() {
using namespace key_suffix;
"caps lock"_key.doSomething();
}

How to resolve a naming conflict between two libraries in C++?

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

Resolving ambiguous calls in C++ with namespaces

I'm merging a static library (assimp) into an existing project (Spring RTS) where both the library and the project are under regular development. I'm trying to add the library in such a way that I can easily repeat the integration as new releases come out.
Anyway, the issue is that Spring requires the library to perform all maths using the streflop maths library. In practice this means min(x,y) should be replaced with streflop::min(x,y) everywhere it is used (which is a lot, considering the issue applies to all maths functions).
I could do a mass regex replace but I was hoping for something a little more elegant. After some research and testing it seemed that adding using namespace streflop; at the top of each .cpp file would do the trick but it didn't.
The exact error is:
/mnt/work/workspace/spring-patch-git/spring/rts/lib/assimp/code/FixNormalsStep.cpp:147: error: call of overloaded sqrtf(const float&) is ambiguous
/usr/include/bits/mathcalls.h:157: note: candidates are: float sqrtf(float)
/mnt/work/workspace/spring-patch-git/spring/rts/lib/streflop/SMath.h:347: note: streflop::Simple streflop::sqrtf(streflop::Simple)
I thought the whole point of namespaces was to resolve this kind of thing but it doesn't seem to work here. I'm a bit confused by the reference to streflop::Simple as well. Is this a nested namespace and could that be part of the reason it isn't working as expected?
If you only need the min function from the streflop namespace, you can use
using streflop::min;
instead of
using namespace streflop;
This will import only the name min, not the whole namespace.
Your error is because what you are doing imports every name from the streflop namespace so that they can be used unqualified, and sqrtf already exists unqualified. Are you perhaps including C header files as they are in C? That is, using math.h instead of cmath? Because if you use the C++ headers like cmath, the functions from the standard library will be in the std namespace and you shouldn't get a clash even if you import the whole streflop namespace.
Another option is that if the places where you now get errors from are few, you can explicitly qualify them. Like in this case, you can replace sqrtf with either streflop::sqrtf or ::sqrtf, depending on which version you want to use.
The streflop::Simple has little to do with your issue; it is just the parameter type and return value for streflop::sqrtf. The only way it is involved is that in overload resolution it gets treated like float so that both of the sqrtf functions listed are possible to call and the compiler cannot determine which one you meant.

Should I wrap all my c++ code in its own namespace?

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>
{
}
}
}