Coder_Dan
Coder_Dan

Reputation: 1882

Is this a reasonable use of namespaces with C++ inheritance hierarchies?

Here is an example of something similar to code I recently wrote, that has proven to be a little contentious at work:

namespace Shape
{
    class Renderer
    {
    public:
        virtual void Draw () = 0;
    };
};

namespace Square
{
    class Renderer : public Shape::Renderer
    {
        virtual void Draw ();
    };
};

namespace Circle
{
    class Renderer : public Shape::Renderer
    {
        virtual void Draw ();
    };
};

The important points are: 1) Within the inheritance hierarchy most classes have the same name but belong to different namespaces 2) 'Renderer' would be just one of several inheritance hierarchies within these same namespaces

My question is: might this ever be a reasonable use of namespaces, or is it an abuse of namespaces? Does anyone else use namespaces in this way?

Having received some comments already, it appears that it may aid the discussion if I point out that in my real-world coding, the namespaces are actually different database technologies, so one is ADO and another is SQLite. Therefore to me the namespaces really are useful groupings.

Upvotes: 3

Views: 180

Answers (2)

Dan Hook
Dan Hook

Reputation: 7078

It is sufficiently different that you need a really strong justification for why you would want to write your code this way. Your co-workers are just looking at the code going "That's really weird," not "That's really weird, but it's really clever because of X." It's not an abuse, it's just unconventional. But without a sufficiently convincing X-factor, unconventional is bad.

Upvotes: 4

vlad_tepesch
vlad_tepesch

Reputation: 6915

In my Opinion, this is a misuse of the namespace concept because you spam the global namespace with sub namespaces.

the purpose of namespaces is to logically group functionality without the need of overlong names and the option for handy usage via using clause (ONLY IN CPP - NEVER IN HEADER).

I would invert the nesting:

namespace Renderer
{
  class BasicShape
  {
    //...
  };

  class Circle: public BasicShape
  {};

  class Sqare: public BasicShape
  {};
}

Upvotes: 3

Related Questions