Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identical class names in different namespaces

I have two different namespaces, with lots of classes with the same name. I believe some code will make it easier to understand:

namespace Print.Pdl.PostScript.Operators
{
    public abstract class BaseOperator : IOperator
    {
         // ...
    }
}

namespace Print.Pdl.Pcl6.Operators
{
    public abstract class BaseOperator : IOperator
    {
         // ...
    }
}

The basic implementation is the same, as PostScript and PCL have similar constructs. So, both namespaces end up having identical names to several classes.

I am tempted to do the following...

namespace Print.Pdl.PostScript.Operators
{
    public abstract class BasePsOperator : IPsOperator
    {
         // ...
    }
}

namespace Print.Pdl.Pcl6.Operators
{
    public abstract class BasePclOperator : IPclOperator
    {
         // ...
    }
}

... but, IMHO, it kind of defeats the purpose, as there is a redundancy in the identification. Why should I prefix/change the classes names, if the namespace already creates a logical barrier?

So, what you people think? Should I keep the identical names, as they are in different namespaces, or should I prefix/change the classes names to make it easier to identify the source, and avoid conflicts if someone wants to use both namespaces together?

Thanks!

like image 903
Ricardo Nolde Avatar asked Apr 19 '11 13:04

Ricardo Nolde


People also ask

Can two namespaces have same name?

You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.

Can a class have the same name as a namespace?

Inside a namespace, no two classes can have the same name.

Can 2 classes have same name in C++?

It violates One Definition Rule.

Can partial classes be in different namespaces?

All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project. Each part of a partial class has the same accessibility.


1 Answers

Nolde,

I don't think you should sacrifice the architecture in favor of readability. I believe its more intuitive if you keep the same class names as this makes it simpler if you are switching from PCL to PostScript and vice-versa.

If you have to use both classes in the same code file, create an alias for the namespace. It will be very clear to read:

using Pcl = Print.Pdl.Pcl6.Operators;
using PostScript = Print.Pdl.PostScript.Operators;
...
// use PCL
Pcl.BaseOperator.DoSomething();
// Use PostScript
PostScript.BaseOperator.DoSomething();

Thanks, Luciano Bargmann

like image 160
Luciano Bargmann Avatar answered Sep 21 '22 08:09

Luciano Bargmann