← 返回首页

Java最佳实践指南

📂 java ⏱ 2 min 396 words

Java最佳实践指南

掌握Java最佳实践能够写出更健壮、可维护和高性能的代码。

编码规范

命名规范

// 类名:UpperCamelCase
public class UserService { }

// 方法名:lowerCamelCase
public void findUserById(String id) { }

// 常量:UPPER_SNAKE_CASE
public static final int MAX_RETRY_COUNT = 3;

// 包名:全小写
package com.example.service;

// 变量名:有意义的命名
int userCount;    // 好
int uc;           // 差

异常处理

// 反模式:捕获所有异常
try {
    doSomething();
} catch (Exception e) {
    // 什么都做不了
}

// 最佳实践:精确捕获
try {
    doSomething();
} catch (FileNotFoundException e) {
    log.error("文件未找到", e);
} catch (IOException e) {
    log.error("IO异常", e);
}

// 使用自定义异常
public class BusinessException extends RuntimeException {
    private final ErrorCode errorCode;

    public BusinessException(ErrorCode errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
}

资源管理

// 最佳实践:try-with-resources
try (var conn = dataSource.getConnection();
     var stmt = conn.prepareStatement(sql)) {
    // 使用资源
}

// 关闭多个资源
try (var input = new FileInputStream("file.txt");
     var reader = new BufferedReader(new InputStreamReader(input))) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}

设计原则

SOLID原则

// 单一职责原则
class OrderService {
    void createOrder(OrderDTO dto) { }
}

// 开闭原则
interface PaymentStrategy {
    void pay(BigDecimal amount);
}

class AlipayStrategy implements PaymentStrategy {
    @Override
    public void pay(BigDecimal amount) { }
}

class WechatPayStrategy implements PaymentStrategy {
    @Override
    public void pay(BigDecimal amount) { }
}

不可变对象

// 最佳实践:使用record或final类
public record User(String name, int age, String email) {
    // 自动不可变
}

// 或手动实现
public final class User {
    private final String name;
    private final int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String name() { return name; }
    public int age() { return age; }
}

性能优化

字符串优化

// 反模式:字符串拼接
String result = "";
for (int i = 0; i < 1000; i++) {
    result += "test"; // 每次创建新对象
}

// 最佳实践:StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append("test");
}
String result = sb.toString();

集合优化

// 反模式:动态扩容
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
    list.add("item" + i); // 多次扩容
}

// 最佳实践:预分配容量
List<String> list = new ArrayList<>(10000);
for (int i = 0; i < 10000; i++) {
    list.add("item" + i); // 无扩容
}

并发最佳实践

// 最佳实践:使用线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
// 或使用ForkJoinPool
ForkJoinPool pool = ForkJoinPool.commonPool();

// 避免使用synchronized,使用ReentrantLock
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // 临界区代码
} finally {
    lock.unlock();
}

// 使用并发集合
ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

小结

遵循最佳实践能够提高代码质量、降低维护成本,是专业Java开发者的基本素养。