Java方法结构案例怎么优化

wen java案例 25

本文目录导读:

Java方法结构案例怎么优化

  1. 方法拆分优化
  2. 参数优化
  3. 流式处理优化
  4. 异常处理优化
  5. 条件逻辑优化
  6. 性能优化
  7. 代码简洁性优化

我来详细解答Java方法结构优化的各种案例和技巧。

方法拆分优化

1 单一职责原则

优化前:

public void processOrder(Order order) {
    // 验证订单
    if (order == null || order.getItems().isEmpty()) {
        throw new IllegalArgumentException("Invalid order");
    }
    // 计算价格
    double total = 0;
    for (Item item : order.getItems()) {
        total += item.getPrice() * item.getQuantity();
    }
    // 应用优惠
    if (order.hasCoupon()) {
        total = total * 0.9;
    }
    // 发送邮件
    EmailService.sendOrderConfirmation(order.getCustomerEmail(), order);
    // 更新库存
    for (Item item : order.getItems()) {
        InventoryService.updateStock(item.getProductId(), -item.getQuantity());
    }
}

优化后:

public void processOrder(Order order) {
    validateOrder(order);
    double total = calculateTotal(order);
    double finalPrice = applyDiscount(order, total);
    updateInventory(order);
    sendConfirmationEmail(order, finalPrice);
}
private void validateOrder(Order order) {
    if (order == null || order.getItems().isEmpty()) {
        throw new IllegalArgumentException("Invalid order");
    }
}
private double calculateTotal(Order order) {
    return order.getItems().stream()
        .mapToDouble(item -> item.getPrice() * item.getQuantity())
        .sum();
}
private double applyDiscount(Order order, double total) {
    return order.hasCoupon() ? total * 0.9 : total;
}
private void updateInventory(Order order) {
    order.getItems().forEach(item -> 
        InventoryService.updateStock(item.getProductId(), -item.getQuantity()));
}
private void sendConfirmationEmail(Order order, double total) {
    EmailService.sendOrderConfirmation(order.getCustomerEmail(), order);
}

参数优化

1 参数对象模式

优化前:

public void createUser(String username, String email, String phone, 
                       String address, int age, String gender) {
    // 创建用户逻辑
}

优化后:

public class UserCreateRequest {
    @NotNull @Size(min = 3, max = 50)
    private String username;
    @Email
    private String email;
    @Pattern(regexp = "^\\d{11}$")
    private String phone;
    private String address;
    @Min(0) @Max(150)
    private int age;
    private String gender;
    // getters/setters
}
public void createUser(UserCreateRequest request) {
    // 创建用户逻辑
}

2 Builder模式

public class QueryBuilder {
    private String table;
    private List<String> columns = new ArrayList<>();
    private Map<String, Object> conditions = new HashMap<>();
    private String orderBy;
    private Integer limit;
    public static QueryBuilder select(String... columns) {
        QueryBuilder builder = new QueryBuilder();
        builder.columns.addAll(Arrays.asList(columns));
        return builder;
    }
    public QueryBuilder from(String table) {
        this.table = table;
        return this;
    }
    public QueryBuilder where(String key, Object value) {
        this.conditions.put(key, value);
        return this;
    }
    public QueryBuilder orderBy(String orderBy) {
        this.orderBy = orderBy;
        return this;
    }
    public QueryBuilder limit(int limit) {
        this.limit = limit;
        return this;
    }
    public String build() {
        StringBuilder sql = new StringBuilder("SELECT ");
        sql.append(String.join(", ", columns));
        sql.append(" FROM ").append(table);
        if (!conditions.isEmpty()) {
            sql.append(" WHERE ");
            conditions.forEach((k, v) -> sql.append(k).append(" = '").append(v).append("' AND "));
            sql.setLength(sql.length() - 4);
        }
        if (orderBy != null) {
            sql.append(" ORDER BY ").append(orderBy);
        }
        if (limit != null) {
            sql.append(" LIMIT ").append(limit);
        }
        return sql.toString();
    }
}
// 使用示例
String sql = QueryBuilder.select("id", "name", "email")
    .from("users")
    .where("status", "active")
    .where("age", 25)
    .orderBy("created_at DESC")
    .limit(10)
    .build();

流式处理优化

1 循环优化

优化前:

public List<String> processUsers(List<User> users) {
    List<String> result = new ArrayList<>();
    for (User user : users) {
        if (user.isActive() && user.getAge() > 18) {
            String processed = user.getName().toUpperCase();
            result.add(processed);
        }
    }
    return result;
}

优化后:

public List<String> processUsers(List<User> users) {
    return users.stream()
        .filter(user -> user.isActive() && user.getAge() > 18)
        .map(user -> user.getName().toUpperCase())
        .collect(Collectors.toList());
}

异常处理优化

1 统一的异常处理

优化前:

public User getUser(Long id) {
    try {
        User user = userRepository.findById(id);
        if (user == null) {
            throw new RuntimeException("User not found");
        }
        return user;
    } catch (Exception e) {
        logger.error("Error getting user: " + e.getMessage());
        throw e;
    }
}

优化后:

public User getUser(Long id) {
    return userRepository.findById(id)
        .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
}
// 全局异常处理器
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.NOT_FOUND.value(),
            ex.getMessage(),
            LocalDateTime.now()
        );
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }
}

条件逻辑优化

1 使用策略模式

优化前:

public double calculatePrice(String userType, double amount) {
    if ("VIP".equals(userType)) {
        return amount * 0.8;
    } else if ("GOLD".equals(userType)) {
        return amount * 0.85;
    } else if ("SILVER".equals(userType)) {
        return amount * 0.9;
    } else {
        return amount;
    }
}

优化后:

// 策略接口
@FunctionalInterface
interface DiscountStrategy {
    double applyDiscount(double amount);
}
// 策略实现
class VipDiscount implements DiscountStrategy {
    @Override
    public double applyDiscount(double amount) {
        return amount * 0.8;
    }
}
// 使用枚举+策略
public enum UserType implements DiscountStrategy {
    VIP(0.8),
    GOLD(0.85),
    SILVER(0.9),
    NORMAL(1.0);
    private final double discountRate;
    UserType(double discountRate) {
        this.discountRate = discountRate;
    }
    @Override
    public double applyDiscount(double amount) {
        return amount * discountRate;
    }
}
public double calculatePrice(UserType userType, double amount) {
    return userType.applyDiscount(amount);
}

性能优化

1 缓存计算结果

优化前:

public int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

优化后:

private final Map<Integer, Integer> cache = new HashMap<>();
public int fibonacci(int n) {
    if (n <= 1) return n;
    return cache.computeIfAbsent(n, key -> {
        return fibonacci(key - 1) + fibonacci(key - 2);
    });
}

2 使用延迟加载

public class HeavyResource {
    private String configuration;
    // 使用Supplier实现延迟加载
    private Supplier<String> configSupplier = this::loadConfiguration;
    private String loadConfiguration() {
        // 模拟耗时加载
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Heavy Configuration Data";
    }
    public String getConfiguration() {
        // 第一次调用时加载,之后直接返回缓存结果
        if (configSupplier != null) {
            configuration = configSupplier.get();
            configSupplier = null;
        }
        return configuration;
    }
}

代码简洁性优化

1 使用Optional避免空指针

public String getCityName(User user) {
    return Optional.ofNullable(user)
        .map(User::getAddress)
        .map(Address::getCity)
        .map(City::getName)
        .orElse("Unknown");
}

2 使用默认方法

public interface ValidationStrategy {
    boolean validate(String input);
    // 默认方法提供组合功能
    default ValidationStrategy and(ValidationStrategy other) {
        return input -> this.validate(input) && other.validate(input);
    }
    default ValidationStrategy or(ValidationStrategy other) {
        return input -> this.validate(input) || other.validate(input);
    }
}

优化Java方法结构的核心原则:

  1. 单一职责:每个方法只做一件事
  2. 参数最小化:控制方法参数数量(最好不超过3个)
  3. 代码复用:提取公共逻辑
  4. 可读性优先:清晰的命名和结构
  5. 性能考虑:适当使用缓存和延迟加载
  6. 错误处理:统一的异常处理机制
  7. 函数式编程:利用Lambda和Stream优化代码

选择优化方案时要权衡:代码可读性、维护性和性能之间的平衡。

抱歉,评论功能暂时关闭!