Re: More or less philosophical thoughts about 'using namespace'
On Mar 31, 6:06 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
Whenever one sees example C++ code basically anywhere, be it
in a book, in a tutorial in the internet, in an online forum
or whatever, I would estimate that at least in 99% of cases one
sees the use of "using namespace std;" to get rid of that
namespace.
You're kidding, right. I see it in beginners' code, but that's
about it. All of the coding guidelines I've used forbid it.
[...]
One reason I have heard is that people think that having to always
write the namespace prefix before all the names is laborious and makes
the code unclear and hard to read. I think this couldn't be farther
from the truth.
Exactly. You write code once, you read it many times. And it
is very laborious reading code which doesn't specify where the
symbols come from. The name of the type is std::string, not
string.
Personally I made the decision many years ago that I will never
use "using namespace" to get rid of a namespace. I quite quickly
got accustomed to always write "std::" before all C++ standard types
and function names and such. Sometimes when I make a library I use
my own namespace name and always put the prefix when I use anything
from the library.
I'll sometimes make an exception for my test suites, e.g.: when
testing Gabi::Toto, I might use a "using namespace Gabi" in the
test code itself. But that's the limit.
I quickly noticed that, instead of making the code unclear,
it actually made the code more readable! Once you become familiar
with the namespace prefixes it actually makes it easier to understand
the code. It makes many things unambiguous and quicker to understand.
Exactly.
[...]
IMO "using namespace" has no use in C++ and only causes lazy people
to write unclear code. I recommend anyone who asks to avoid writing
it altogether. The first few hundreds of lines of code might feel a
bit awkward, having to write all those extra "std::" prefixes, but
I assure that it very quickly becomes like a second nature to write
them, and they very quickly stop looking like garbage and instead they
become the exact opposite.
You don't have to ask. It's a common rule in the coding
guidelines of any serious company.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34