【3分钟知识】学习低耦合思维之后再也不写shi山代码

为什么大型项目需要低耦合?

代码萌新喜欢写高耦合(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"; // 假设永远成功(别学!)
    }
}

问题爆炸点

  1. 支付逻辑和数据库操作硬编码在订单类里。
  2. 换支付方式要改OrderService全身代码。
  3. 测试时必须连数据库+支付接口。

正确姿势:拆分核心职责,通过接口解耦
// 低耦合版:
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实现
}

解耦优势

  1. 支付方式自由切换:新增微信支付只需实现PaymentGateway,无需改动订单服务。
  2. 独立测试:单元测试OrderService时,可以传入Mock的支付和仓库实现。
  3. 职责单一:每个类只做一件事(如支付、存储),符合SOLID原则。

萌新写代码应拷问自己:
  1. 优先用接口抽象:遇到“new具体类”的地方,先问“能不能抽象成接口?”
  2. 依赖注入:学会用Spring的@Autowired或构造器注入,别什么东西都扔到一个类里。
  3. 隔离外部依赖:数据库、支付等外部服务,用Wrapper类包装(如PaymentGateway)。

低耦合就像“用插头代替焊接”——前期多花5分钟设计,后期能省3天 debug时间(如果你想带薪摸鱼除外,关于这点欢迎交流,向大家学习哈哈)。在代码里留出扩展钩子,才是真正的高手思维。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值