Standard Library Code Bad Practice

I figured I might address this, in case some students come in and might have got a shortcut for this from a friend or co-worker.
There does exist a sort-of ‘bad practice’ for coding where you use the following code:

#include
using namespace std;

What this essentially does is allow you to declare that you are using the namespace ‘std’ in this code from the string library. This would allow you to declare the string variables without having to use the std and scope resolution operator. So instead of:

std::string knightHealth = "Health: ";

We can use:

string knightHealth = "Health: ";

Anywhere we need to access a function with scope resolution, we can ignore the std declaration.
HOWEVER…this is bad practice for the following reasons:

If something changes with functions in the standard library, or say some code is created that later changes the way a standard library function behaves, this could most definitely break your code that you may have typed years ago. The reason being is that using ‘namespace’ imports the entirety of the std namespace into the current namespace of the program.

“Namespaces were introduced into C++ to resolve identifier name conflicts. This ensured that two objects can have the same name and yet be treated differently if they belonged to different namespaces. When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. It has hundreds of predefined identifiers, so it is possible that a developer may overlook the fact there is another definition of their intended object in the std library”.

So while it may be tempting to save some typing and make the code look cleaner or easier to read, it is not a good idea to declare the use of a namespace and instead simply use the scope resolution operator to tell the compiler where you are getting your namespaces.

If I am off on my information, someone feel free to correct or add to this.

-C

3 Likes

As far as the C++ Standard Library goes (namespace std) it is unlikely that there will be breaking changes in the future. I suppose there is a possible conflict were the Standard Library expanded with additional declarations.

I endorse your approach however. I think having explicit namespace dependencies in appeals to library-defined entities is a great idea, since it disambiguates in an explicit way. I think this is important especially for novices where good practices begin with code that is unambiguous in future readings and also trouble-shooting (and keeping intellisense as your friend).

If one might want to use a different namespace or library in the future (e.g., for an alternative string implementation say), it is possible to get help from the preprocessor on that. That’s beyond-novice anticipation, seems to me.

1 Like

Privacy & Terms