| 元素 | 規則 | 正例 | 反例 |
|---|---|---|---|
| Package | 全小寫,單數名詞,多級用點分隔 | com.company.project.module | com.Company.Project |
| Class/Interface | UpperCamelCase,名詞/形容詞 | UserService, Serializable | user_service, User_Service |
| Method | lowerCamelCase,動詞/動詞短語 | getUserById, saveOrUpdate | GetUserById, get_user_by_id |
| Variable/Parameter | lowerCamelCase,名詞 | userName, pageSize | UserName, user_name |
| Constant (static final) | UPPER_SNAKE_CASE | MAX_RETRY_COUNT, DEFAULT_TIMEOUT | MaxRetryCount |
| Array | 類型後置 Type[] name | byte[] buffer | byte buffer[] |
public class X extends Y implements Z,extends/implements 換行toString()、equals()/hashCode()、clone() 等通用方法/**
* 根據 ID 查詢用戶
* @param id 用戶主鍵,必須 > 0
* @return 用戶對象,不存在返回 null
* @throws IllegalArgumentException id <= 0
* @throws DataAccessException 數據庫訪問異常
*/
public User findById(long id) throws DataAccessException {
if (id <= 0) throw new IllegalArgumentException("id must > 0");
// ...
}
public class User {
public User() { this(0, null); }
public User(long id) { this(id, null); }
public User(long id, String name) {
this.id = id;
this.name = name;
}
}
@Override
public User clone() {
try {
User cloned = (User) super.clone();
// 深拷貝可變字段
cloned.tags = new ArrayList<>(this.tags);
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError("實現 Cloneable 不可能拋出此異常", e);
}
}
使用 Objects.toStringHelper(this) (Guava) 或手寫格式:User{id=1, name='张三'},包含所有關鍵字段,便於日誌診斷。
codestyle.xml(IntelliJ)或 formatter.xml(Eclipse)。maven-checkstyle-plugin、spotbugs-maven-plugin、pmd-maven-plugin 做 CI 門禁。