为什么大型项目需要低耦合?
代码萌新喜欢写高耦合(shi山)代码,导致后期维护不易,测试不易,拓展不易,作为一个长期在这上面走弯路的萌新,写出来的代码像“黏在一起的积木”——改一块就得拆一堆。在大型项目中,这会引发:
维护噩梦:一个类改动可能瘫痪整个模块。
扩展困难:新增功能需要暴力修改现有代码。
测试陷阱:单元测试需要连带依赖的几十个类。
队友埋怨:队友看了想砸键盘难以理解没法接手。
高耦合代码反面案例:订单处理类直接“绑架”支付逻辑
public class OrderService {
private static final String PAYMENT_URL = "https://apiipay.com/pay";
public void createOrder(Order order) {
// 1. 调用支付接口
String paymentResult = sendPayment(order.getAmount());
// 2. 直接硬编码数据库操作
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db")) {
String sql = "INSERT INTO orders (user_id, total) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, order.getUserId());
pstmt.setDouble(2, order.getTotal());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if (paymentResult.equals("SUCCESS")) {
System.out.println("订单创建成功!");
} else {
System.out.println("支付失败,订单取消...");
}
}
private String sendPayment(double amount) {
// 模拟支付接口调用
return "SUCCESS"; // 假设永远成功(别学!)
}
}
问题爆炸点:
- 支付逻辑和数据库操作硬编码在订单类里。
- 换支付方式要改
OrderService
全身代码。 - 测试时必须连数据库+支付接口。
正确姿势:拆分核心职责,通过接口解耦
// 低耦合版:
public interface PaymentGateway {
String processPayment(double amount);
}
public class OrderService {
private final PaymentGateway paymentGateway;
private final OrderRepository orderRepository;
// 依赖注入(Spring Boot为例)
public OrderService(PaymentGateway paymentGateway, OrderRepository orderRepository) {
this.paymentGateway = paymentGateway;
this.orderRepository = orderRepository;
}
public void createOrder(Order order) {
if (paymentGateway.processPayment(order.getAmount()).equals("SUCCESS")) {
orderRepository.save(order);
System.out.println("订单创建成功!");
} else {
System.out.println("支付失败,订单取消...");
}
}
}
// 支付模块实现
public class AlipayPayment implements PaymentGateway {
@Override
public String processPayment(double amount) {
// 调用支付宝API的逻辑
return "SUCCESS"; // 实际业务需要处理异常
}
}
// 数据库模块实现
public interface OrderRepository {
void save(Order order);
}
public class JpaOrderRepository implements OrderRepository {
// JPA实现
}
解耦优势:
- 支付方式自由切换:新增微信支付只需实现
PaymentGateway
,无需改动订单服务。 - 独立测试:单元测试
OrderService
时,可以传入Mock的支付和仓库实现。 - 职责单一:每个类只做一件事(如支付、存储),符合SOLID原则。
萌新写代码应拷问自己:
- 优先用接口抽象:遇到“new具体类”的地方,先问“能不能抽象成接口?”
- 依赖注入:学会用Spring的
@Autowired
或构造器注入,别什么东西都扔到一个类里。 - 隔离外部依赖:数据库、支付等外部服务,用Wrapper类包装(如
PaymentGateway
)。
低耦合就像“用插头代替焊接”——前期多花5分钟设计,后期能省3天 debug时间(如果你想带薪摸鱼除外,关于这点欢迎交流,向大家学习哈哈)。在代码里留出扩展钩子,才是真正的高手思维。