1. 命名规范
类名
- 规则:使用大驼峰命名法(PascalCase),首字母大写,使用名词或名词短语。
- 示例:
public class UserAccount { // 类内容 }
方法名
- 规则:使用小驼峰命名法(camelCase),首字母小写,使用动词或动词短语。
- 示例:
public void calculateTotalPrice() { // 方法实现 }
变量名
- 规则:使用小驼峰命名法,避免缩写(除非通用,如
id
、num
)。 - 示例:
private String customerName; int orderCount = 0;
常量名
- 规则:全部大写,单词间用下划线分隔。
- 示例:
public static final int MAX_RETRY_COUNT = 3;
2. 代码格式
缩进
- 规则:使用 4 个空格(而非 Tab)缩进。
- 示例:
if (condition) { // 4个空格缩进 System.out.println("Hello"); }
行宽
- 规则:每行不超过 120 个字符,长表达式需换行。
- 示例:
String result = longMethodName(param1, param2, param3, param4);
括号位置
- 规则:左括号不换行,右括号单独占行(非强制)。
- 示例:
public void method() { // 方法体 }
3. 注释规范
类注释
- 规则:使用 Javadoc 描述类的用途和设计。
- 示例:
/** * 表示系统中的用户账户,包含基本信息和操作方法。 * @author doubao * @since 2025 */ public class UserAccount { // ... }
方法注释
- 规则:使用 Javadoc 描述功能、参数、返回值和异常。
- 示例:
/** * 计算订单的总价格。 * @param discount 折扣率(0.0-1.0) * @return 折扣后的总价格 * @throws IllegalArgumentException 如果折扣率无效 */ public double calculateTotalPrice(double discount) throws IllegalArgumentException { // ... }
代码注释
- 规则:解释复杂逻辑或特殊处理。
- 示例:
// 处理边界情况:当数量为0时直接返回 if (count == 0) { return 0; }
4. 面向对象原则
单一职责原则(SRP)
- 规则:一个类只负责一项职责。
- 示例:
// 正确:User类负责用户信息管理 public class User { private String name; public String getName() { return name; } } // 错误:将用户信息和数据库操作混合 public class User { public void saveToDatabase() { /* ... */ } // 违反SRP }
开闭原则(OCP)
- 规则:对扩展开放,对修改关闭(通过接口 / 抽象类)。
- 示例:
// 定义接口 public interface PaymentMethod { void pay(double amount); } // 实现类 public class CreditCardPayment implements PaymentMethod { @Override public void pay(double amount) { /* ... */ } }
5. 异常处理
检查型异常(Checked Exception)
- 规则:使用
throws
声明或try-catch
捕获。 - 示例:
public void readFile(String path) throws IOException { FileReader reader = new FileReader(path); // ... }
非检查型异常(RuntimeException)
- 规则:避免在方法签名中声明,通过代码逻辑预防。
- 示例:
public void divide(int a, int b) { if (b == 0) { throw new IllegalArgumentException("除数不能为0"); } // ... }
6. 资源管理
try-with-resources
- 规则:自动关闭实现
AutoCloseable
的资源。 - 示例:
try (FileInputStream fis = new FileInputStream("file.txt")) { // 使用fis读取文件 } // 自动关闭fis
7. 集合与泛型
泛型集合
- 规则:优先使用泛型,避免原始类型。
- 示例:
// 正确 List<String> names = new ArrayList<>(); // 错误(原始类型) List names = new ArrayList();
不可变集合
- 规则:返回不可变视图,防止外部修改。
- 示例:
private List<String> data = new ArrayList<>(); public List<String> getData() { return Collections.unmodifiableList(data); }
8. 并发编程
线程安全
- 规则:对共享资源使用
synchronized
或并发工具类。 - 示例:
public class Counter { private int count = 0; public synchronized void increment() { count++; } }
线程池
- 规则:使用
ExecutorService
管理线程,避免手动创建线程。 - 示例:
ExecutorService executor = Executors.newFixedThreadPool(5); executor.submit(() -> { // 任务逻辑 });
9. 单元测试
JUnit 5 示例
- 规则:为每个方法编写测试用例。
- 示例:
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { @Test public void testAdd() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } }
10. 依赖管理
Maven 依赖示例
- 规则:使用工具管理依赖,避免手动引入 JAR 包。
- 示例(
pom.xml
):<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.9</version> </dependency> </dependencies>
11. 日志规范
SLF4J 日志示例
- 规则:使用 SLF4J 而非
System.out.println
。 - 示例:
private static final Logger logger = LoggerFactory.getLogger(MyClass.class); public void process() { logger.info("开始处理数据"); try { // 业务逻辑 } catch (Exception e) { logger.error("处理失败", e); } }
12. 代码复用
组合优于继承
- 规则:通过组合实现代码复用,而非继承。
- 示例:
// 组合方式 public class Car { private Engine engine; // 组合 public void start() { engine.start(); } }
13. 安全规范
SQL 注入防护
- 规则:使用预编译语句(
PreparedStatement
)。 - 示例:
String sql = "SELECT * FROM users WHERE username = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, username);
14. 版本控制
Git 提交规范
- 规则:提交信息清晰,使用动词开头。
- 示例:
git commit -m "修复用户注册时的空指针异常"
15. 其他建议
-
避免空指针:使用
Objects.requireNonNull()
或 Optional。String name = Optional.ofNullable(user.getName()) .orElse("未知");
-
避免魔法数字:定义常量替代硬编码值。
// 错误 if (score > 90) { /* ... */ } // 正确 private static final int PASS_SCORE = 90; if (score > PASS_SCORE) { /* ... */ }
-
接口设计:保持接口单一职责,避免臃肿。
// 错误:大而全的接口 public interface UserService { void createUser(); void sendEmail(); // 与用户管理无关 } // 正确:拆分接口 public interface EmailService { void sendEmail(); }