Your header should not pollute my program

After decades of sometimes bitter experience, we know how to create proper C++ headers.  No doubt the single greatest advance has been multiple-inclusion prevention, first done in C:

/* various includes and header declarations *

This mechanism in turn allows us to achieve the goal that every C++ header should be self-contained.  That is, including one header should never require another include directive above it.  Even better, and believe me, this is huge, the order of your include statements should not matter. (It may be hard to imagine the sheer Hellishness, but this has not always been the case.)

In addition to being complete, however, a header file should be minimal.  It should not bring in any declarations except those needed for the header to compile.  Some rookie programmers make the mistake of using the class header file to include headers only needed by the implementation:

#include <stack>
class MyStackImpl;
class MyIntStack
    MyIntStack(MyStackImpl *pimpl, unsigned int max);
    void push(int);
    int pop();
// No reference to std::stack???  Don't do this!

This not only makes it harder for people to use your class, but it inhibits changing your implementation.

It’s a good idea to declare a namespace in your header.  What the heck, they are free, and if you avoid having to resolve name collisions between your stuff and someone else’s, you’ve done yourself a huge favor.

Finally, and here is where I get eye-rolls, a header should NEVER NEVER NEVER include a “using namespace” directive.  Not even “std”.

#include <string>
using namespacee std;
string generateRandomString();

If the interface you declare refers to classes or methods from namespaces, then man up and use explicit namespaces.  E.g.,

#include <string>
namespace simple_example
std::string generateRandomString(); //was that so hard?

Because maybe, just maybe, I have my reason for not wanting this namespace in my program.

Whether that’s the case or not, what is certain is that you would be wrong to force “using” a namespace on me.

2 thoughts on “Your header should not pollute my program

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s