简体   繁体   中英

Is it a good practice to have a package/namespace and class within with the same name?

I 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:

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:

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM