Is it a good practice to have a package/namespace and class within with the same name?
I开发者_JS百科 am creating a new namespace and the most apt name for one of the class seems to be the same name as the namespace. Is this a good practice? If not, what is the alternative?
For example:
com.person
|--- Person.(java/cs)
|--- PersonDetailChecker.(java/cs)
|--- PersonNameGenerator.(java/cs)
Related questions discussing the same issue:
- Should a class have the same name as the namespace?
- How to avoid having the same name for a class and it's namespace, such as Technology.Technology?
I would try to avoid that, since it can make your code harder to read Eric Lippert has written an article about this, which you can find here:
part 1,
part 2,
part 3
part 4
I've made the mistake myself a few times, and it certainly made it harder to read some of my code.
It is no problem to do this in Java.
But it is NOT a good practice: because a good practice would mean, that you should do it. (And that is clearly not the fact.).
BTW. In Java, the class name should start with an upper case letter, and packages should only contain lower case, to they are never realy the same -- this is good practice.
Added After rethining the for a while I think it is an indication of an Architectural failure if the package and class have the same name. The reason is: that everything should have its own unique reason to exist, and its name should indicate the reasons. So if you have a package and a class with the same name, then its reason of exisiting is not unique, or its names are bad.
In Java the simple fact that your package name should be all lowercase and your class name should begin with an uppercase letter guarantee that they won't clash. If they are the same, you must have violated one of these guidelines, which is a more fundamental stylistic problem than your specific one.
As long as the case is different, no problem. However, as soon as you use the same exact identifier for a namespace and an object, you end up having to fully qualify your references to that object (which makes the code rather verbose and ugly IMHO).
I would go out of my way to make class names unique, and self explanatory, within a reasonable scope, regardless of package. A class name with one word is quite confusing, unless it's a well known, generally accepted name, for a common concept.
A nested class is kind of in the name space of the enclosing class. People may do this
class Http
class Request
enum Method
class Response
class Code
Http.Request.Method.GET
new Http.Response.Code(123);
While I find this quite readable, I'd still stick to the old style
class Http
class HttpRequest
enum HttpRequestMethod
class HttpResponse
class HttpResponseCode
HttpRequestMethod.GET
new HttpResponseCode(123);
精彩评论