3 years ago

Namespaces? Do I need them? Are they evil?


When I began my lessons in C++, well lessons, rather reading some internet courses, I've seen a lot of discussion about them. Most of all should you use namespaces, and if you do, should you be using the "using" keyword to call them....

Now the only two languages I've worked with where namespaces are very commonly used are C# and C++, but undoubtedly more languages exist.

In C++ I do not see everybody using them, however in C++ we also have to take compatibility with C in mind, and C does, as far as I know not support namespaces. In C# it's always considered bad practice not to use them... When you use VisualStudio, namespaces will even be automatically created for you, however also along with the "using" command, voiding the effect of namespaces... at least according to some coders.... I disagree with that one, although in C++ things are a bit more complicated than in C# in regard of namespacing and the "using command".

For those who never worked with languages supporting namespaces, first the answer to the question what a namespace is... It's actually nothing more but a kind of safeguard to prevent code conflicts, in case you use libraries from multiple creators and have your libraries conflict with theirs due to functions and stuff having the same name. The fact that both C# and C++ support function overloading does not always save your ass here... As a matter of fact they can even make things more troublesome.

What *is* a namespace?

Now thanks to namespaces you can always make sure conflicts say out of the way. Like this:

		
			#include <iostream>

namespace English {
 void Greet() { std::cout << "Hello World\n"; }
}

namespace Dutch {
 void Greet() { std::cout << "Hallo Wereld\n"; }
}

int main() {
 English::Greet();
 Dutch::Greet();
}
		
	

Now we have two functions with the same name, since the parameter setup is the same for both, function overload won't help here. However thanks to the namespaces, the compiler always knows what is what and no errors due to conflicts.

Now as you can see in C++ :: is used to separate a namespace from the actual identifiers (all identifiers, functions, classes, variables, whatever, doesn't matter), and you see "cout" (which means "console output") also being prefixed with "std::". Yes "std" is also a namespace, and all stuff in the <iostream> library is part of this namespace.

The "using" keyword.

Now this is a keyword open for debate. Having to type the same prefix all the time is not what you want... In Dutch we call that "gekkenwerk" (literally: Idiot's work). The "using" keyword can help here, but the usage of it is controversial.

Let's take the example above.

		
			#include <iostream>
using namespace std;

namespace English {
 void Greet() { cout << "Hello World\n"; }
}

namespace Dutch {
 void Greet() { cout << "Hallo Wereld\n"; }
}

int main() {
 English::Greet();
 Dutch::Greet();
}
		
	

Now thanks to the "using namespace std" command just after my "#include", I don't have to type std:: before all cout commands. Saves a lot of typing, and it keeps code even cleaner in several cases. However, here's the "evil"... You see two namespaces in my code... Yes "using namespace English" and "using namespace Dutch" can just be added, no problem there, but here's the rub.... How to distinguish the two greet commands now? The compiler won't know, and throw an error UNLESS you just keep the prefixes the way they are. Since std has no functions named "Greet" no problem with "using namespace std" in this particular example.

Now when coding in C++ (in C# this ain't an issue) you must take something VERY EXTREMELY important in mind, at least when you create libraries for multiple projects.... The HEADER files! Header files are included in the main code of the project, and that includes "using" commands. So if I make this header:

		
			#include <string>
using namespace std;

string mystring();
		
	

Then 'std' will be in "using" in the code of all code files including that header. You do NOT want that, and even in header files you only use in one program I recommend against it. I made that mistake in my first stuff and regret it now. In header files it's technically forbidden to use "using"... The compiler will pick it up fine, but it can work out terribly. If you really want to use "using" in the main source, all fine, but never in headers...

Well I did find a way to cheat, but you should know what you are doing:

		
			#include <string>
namespace Tricky{
    using namespace std;
    string MyString();
}
		
	

"using" will in C++ only affect the scope within it's called, meaning that the "using std" will affect the string MyString() header itself, but not the code including this header. This is considered dirty code straight from Hell, though.

Namespaces in C#

The basic functionality is the same as in C++, however here are a few differences. First of all in stead of "::" you use a ".", andthe "using" keyword only needs the name of the namespace and not the keyword "namespace" (this is because the "using" keyword in C++ is a bit more sophisticated than its C# counterpart)

		
			using System;
namespace Prog {
 class Hi {
  static void Main() {
     Console.WriteLine("Hello World!");
  }
 }
}
		
	

Console.WriteLine is actually System.Console.WriteLine, however thanks to "using System" we don't have to use "System" all the time. Now as "Prog" is a namespace containing a program in stead of a library, why a namespace? You may even wonder that since in C# nothing can live outside a class why namespaces are even needed at all? Well, it has a use, trust me!

		
			namepace Mine {
 class Console {
    void Hello() {
       System.Console.WriteLine("Hello World");
    }
 }
}
		
	

If I call the class "Console" now, which class do we need? The "Mine" version or the "System" version? No way for the compiler to know... Thanks to namespaces that problem has been solved. Now in C# I deem the chance for conflicts due to the strict class system not that likely, but still, since namespaces are easy to create, it can save you a lot of trouble.

What does make the C++ "using" more sophisticated?

The C# variant can only do this with namespaces. C++ can use more specific stuff in namespaces. Like this:

		
			#include <iostream>
using std::cout;
int main() {
    cout << "Hello world!\n";
}
		
	

If you would use other "std" functions now you'd still have to prefix them with "std", but only "cout" doesn't require that anymore. As "using" is considered dangerous, you can that way just limit the "dangers" by only going for that stuff you expect to need most.

Is it so bad to be using "using"?

If you ask me, if you can at least prevent stuff being set with "using" automatically by simply including the header file, I think you are all fine. In C++ all regular code files need to be compiled separately anyway and that way there is no way in which a using-command in one file can affect the other.... Only headers which are always literally merged with your code while compiling should be "using" free or the "using" commands not being used where they can affect code not part of the header. You should just be aware if what functions can be part of the namespace so they don't conflict with your own code, or other libraries. Since you can still add the prefix in case of a possible conflict I don't wanna use the word "dangerous", but having to change over thousands of lines of code, simply because of importing another library later which can cause identifier conflicts does really suck. So while "using" is meant to save your work, it's in theory possible they give you more work. Some people prefer to only use "using" inside functions, but then only functions that are bigger than other functions or in which a certain identifier within a namespace is used a crapload.

I am not really against "using"... I actually use it in my C++ code myself, however, if you use it, be aware of the consequences, and keep them in mind as you write your code.

In C# it's common to always be using the "using" keyword, but keep in mind, in C# you don't need to make header files (as C# has an automated system for that) and "using" of one file can not affect the other (in C# you cannot use the word "using" inside a scope of function anyway, as far as I know). Of course, VisualStudio is also a big help in quickly finding namespace conflicts which "using" may cause....

So when it comes to the debate about "using"...

Decide yourself what is best, but avoid them in header files!



0 comments

Loading...

Next up

Current situation on TFT REVAMPED

Game redo on Cynthia Johnson

A few facts and fables about fire.

Happy Video Game Day! 🎮

Celebrate by completing our quests!

(They'll be in your quest log until September 19th.)

Celebrities (almost) killed by one of their biggest fans

@GabrieleGiuseppini has added exclusive Floating Sandbox avatar frames, stickers, and backgrounds for all of you!

Set sail to the shop and collect 'em all! https://gamejolt.com/#shop

#gjbroadcast

Why do people wanna be a #moderator? Is it really such a #cooljob?

Disney Princesses go to Hogwarts

Happy #WIPWednesday!

Are you working on a game?

Making some art?

Practicing a song?

Something else?

Tell us in the comments!

A #phrase of #wisdom from the French scientist and philosopher #BlaisePascal Two stories, the one tied to this game (new version), and a prequel novel based on this game have this quote. Perhaps you understand why....