简体   繁体   English

Java“用户”类命名最佳实践?

[英]Java “User” class naming best practice?

I'm about to create a User class for my project. 我即将为我的项目创建一个User类。 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. 我可以使用特定于我的项目的前缀来补充它。

这是包的目的。

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. 您可能很容易最终使用具有“用户”类或接口的API。 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. 虽然最新的IDE使得重构代码变得相对容易,但如果你有一个特定于应用程序的“用户”类,它会更简洁。

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. 请记住创建适当的包,以更具体地定义您的类。

I always try to use common names like User for clarity. 为了清楚起见,我总是尝试使用像User这样的常用名称。 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. 具有自动重构支持的现代IDE使这一切变得简单。

You should use Java package s to avoid name clashes. 您应该使用Java package来避免名称冲突。 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: 然后,您使用以下命令开始文件“User.java”:

package com.yourwebsite.yourproject.userdata;

When you import it, you would use: 导入时,您将使用:

import com.yourwebsite.yourproject.userdata.User;

此名称不太可能被任何公共API使用,因此应用程序可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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