tags:

views:

102

answers:

6

I'm about to create a User class for my project. Any opinions as to whether it is bad practice to create such a commonly-named class? I could complement it with a prefix specific to my project.

+2  A: 

This is what packages are for.

Ian Henry
Well you might end up importing two packages having "User" class. That would probably cause some headaches.
Ravi Gummadi
@Ravi, but if that were to be an issue, then you could refer to the classes by their fully qualified names.
Michael Aaron Safyan
@Michael: That's true, but I feel that it hurts the readability of the code.
Ravi Gummadi
+1  A: 

Using common names is not a bad practice, until and unless you describe the name as that to the functionality of the class. keep in mind to create proper packages that can define your class more specifically.

Mrityunjay
+1  A: 

I would suggest you to definitely prefix an application specific term to your User class. "User" is way too common and vague. You might easily end up using API which has "User" class or Interface. Though latest IDEs make it relatively easy to refactor your code, it would be cleaner and easier if you have a app specific "User" class.

Ravi Gummadi
I agree with you. It starts becoming a mess when you have multiple classes with same name.
Ankit
A: 

You should use Java packages to avoid name clashes. There is nothing wrong with using a common name, just be sure to put it in its own package. For example, you could have the following structure:

com/
  yourwebsite/
      yourproject/
            userdata/
                 User.java

You then begin the file "User.java" with:

package com.yourwebsite.yourproject.userdata;

When you import it, you would use:

import com.yourwebsite.yourproject.userdata.User;
Michael Aaron Safyan
I would still suggest that people do not name their classes "String" or "List" or "Collection" or "Exception" or "Connection" or "Session". I am fine with "User", if only because it is not commonly used elsewhere (in my current workspace, which has many libraries, there is only one in "com.sun.tools.internals..." and one in "org.hsqldb", none of which you are likely to use).
Thilo
@Thilo, yeah, I certainly would not use names that are already in use in any of the "java.*" or "javax.*" packages, but there is no User class in the Java API as of this writing.
Michael Aaron Safyan
+1  A: 

I always try to use common names like User for clarity. Just be sure the names are drawn from the problem domain and existing project vocabulary. Be alert for ambiguities, and if one arise, change the class name. Modern IDEs with automated refactoring support make that easy.

Jim Ferrans
Yes. Having correct class name in appropriate package will be the right thing. IDEs like IntelliJ very good support for searching and importing class names - it can be even automatic.
Jayan
A: 

This name is unlikely to be used by any public API, so it's ok for an app to use it.

irreputable