C++ – Should class names reflect namespace name

cdesignnamespacenaming

Is it generally considered good practise for a class name to reflect the namespace name it exists under, or should the namespace name implicitly be considered part of the class name?

For example, suppose I have a collection of classes which all act to filter a class Foo:

class FooFilter
{
    public virtual bool operator()(const Foo& obj) const = 0;
};

Subtypes could be called HappyFooFilter, SadFooFilter, … etc.

Now if we wrap these into a namespace, we have something like:

namespace fooFilter
{
    class FooFilter ...
    class HappyFooFilter ....
    class SadFooFilter ...
    etc ....
}

But this contains a redundancy in the class names (e.g. fooFilter::HappFooFilter). So with the introduction of the namespace fooFilter, should the class names change to reflect this new structure?

namespace fooFilter
{
    class Base ...
    class Happy ....
    class Sad ...
    etc ....
}

Best Answer

The problem is that your example is vague and your names are anemic. If we make them good robust names doesn't the choice become obvious?

namespace ImageFilter
{
     class BasicFace ...
     class HappyFace ...
     class SadFace ...
}

verses

namespace ImageFilter
{
     class BasicFaceImageFilter ...
     class HappyFaceImageFilter ...
     class SadFaceImageFilter ...
}

This smurf naming anti pattern has tempted me in the past as well. I've come to feel it's the result of trying to keep anemic names on life support. Rethink all the names and try again. It's a pain to do but it makes for better code.