写clean code 笔记

该视频笔记https://www.youtube.com/watch?v=MKaLJyPOS4U

  1. Guard clauses
  2. Single Responsibility Principle (SRP)
    单一职责原则 (SRP)
    : SRP 是面向对象设计的五大原则之一。
    Long Functions长函数: 长函数通常被认为是不好的做法,因为它们可能难以阅读、理解和维护。一个好的做法是将长函数重构成更小、更易管理的函数。每个小函数应该执行单一任务或一系列紧密相关的任务,这让代码更加模块化和可重用
    // 原始的长函数
    function processOrder(order) {
      // 验证订单
      if (!order.isValid) {
        throw new Error('Invalid order');
      }
    
      // 计算总价
      let total = 0;
      for (let item of order.items) {
        total += item.price * item.quantity;
      }
    
      // 应用折扣
      if (order.discount) {
        total = total * (1 - order.discount);
      }
    
      // 发送通知
      console.log(`Order processed: ${total}`);
    }
    
    // 重构后的短函数
    function validateOrder(order) {
      if (!order.isValid) {
        throw new Error('Invalid order');
      }
    }
    
    function calculateTotal(order) {
      return order.items.reduce((total, item) => total + item.price * item.quantity, 0);
    }
    
    function applyDiscount(total, discount) {
      return total * (1 - discount);
    }
    
    function sendNotification(total) {
      console.log(`Order processed: ${total}`);
    }
    
    function processOrder(order) {
      validateOrder(order);
      let total = calculateTotal(order);
      if (order.discount) {
        total = applyDiscount(total, order.discount);
      }
      sendNotification(total);
    }
    

猜你喜欢

转载自blog.csdn.net/2301_78916954/article/details/143240555