Bad practice to have two classes of the same name

2020-04-02 08:13发布

问题:

We have split our application so that package A handles data from one external source and package B from another. In both cases we need to create a domain object and have a "Transformer" to do this.

So I have com.foo.bar.a.ThingTransformer and com.foo.bar.b.ThingTransformer

I suspect that this is poor practice, but want to see what the good people of SO think.

回答1:

I wouldn't go as far as saying that it's always a bad practice, but it's somewhat of a code smell.

If both classes do different things, then why don't they have different names?

if both classes do the same thing, then why are there two classes?

From a practical standpoint it can become very annoying if those two classes ever need to be referenced in the same class: you'll have to use the FQN for one of those (it would probably be best to use it for both in this case, for clarity). If those two classes are in sufficiently distinct parts of the code that they won't be referenced from the same code, then the practical problem is not so bad.



回答2:

Not really poor practice, as in many domains have similar terminology, so you will end-up having same names. On the other hand if both are in same domain, but simply different implementations, you can (somehow) indicate the implementation specifics in the name.
The very ugly thing would be if you have to use both in same source file, in this case you have to use fully qualified name for at least one.

Examples:

java.util.List java.awt.List

indicate implementation in the name:
java.util.ArrayList
java.util.LinkedList



回答3:

It's fine. This is precisely why, by design, different packages have different namespaces.



回答4:

Nothing wrong with that, since it's very unlikely you'll use both classes together in the same code. Duplicating the a/b distinction from the package in all class names would be worse.



回答5:

You have to decide if this is more helpful or more confusing. You can get the same problem with using similar names in the same package where the difference is not clear.

An example of more-confusing-than-helpful is something like

com.sun.corba.se.internal.Interceptors.PIORB extends
com.sun.corba.se.internal.POA.POAORB which extends
com.sun.corba.se.internal.iiop.ORB which extends    
com.sun.corba.se.impl.orb.ORBImpl which extends
com.sun.corba.se.spi.orb.ORB which extends    
com.sun.corba.se.org.omg.CORBA.ORB which extends
org.omg.CORBA_2_3.ORB which extends
org.omg.CORBA.ORB