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:

#ifndef MY_HEADER_FILE_H
#define MY_HEADER_FILE_H
/* various includes and header declarations *
#endif

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:

#ifndef TOO_MUCH_IN_HEADER_H
#define TOO_MUCH_IN_HEADER_H
#include <stack>
class MyStackImpl;
class MyIntStack
{
:public
    MyIntStack(MyStackImpl *pimpl, unsigned int max);
    ~MyIntStack();
    void push(int);
    int pop();
};
#endif
// 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”.

#ifndef BAD_EXAMPLE_H
#define BAD_EXAMPLE_H
#include <string>
// DON"T DO THIS!!!
using namespacee std;
string generateRandomString();
#endif

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

#ifndef GOOD_EXAMPLE_H
#define GOOD_EXAMPLE_H
#include <string>
namespace simple_example
{
std::string generateRandomString(); //was that so hard?
}
#endif

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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s