重构手法——对象结构优化类 | 类关系解耦 | 内联临时变量

44 阅读4分钟

简介

“内联临时变量”(Inline Temp)是一种重构手法,通过将临时变量的使用替换为其赋值表达式,从而简化代码。这种方法适用于那些只被使用一次且表达式简单的临时变量。以下是进行“内联临时变量”重构的详细步骤:

针对的症状(代码坏味道)

  • 不必要的临时变量(Unnecessary Temporary Variable)
  • 表达式简单且只使用一次的临时变量(Simple Expression Used Once)

内联临时变量(Inline Temp)的详细步骤

  1. 识别需要内联的临时变量
    • 寻找只被使用一次的临时变量。
    • 确保临时变量的赋值表达式简单且易于理解。
  2. 替换临时变量
    • 将临时变量的使用替换为其赋值表达式。
    • 删除临时变量的声明和赋值语句。
  3. 测试
    • 编译代码:确保代码编译通过,没有任何语法错误。
    • 运行测试:运行所有相关的单元测试,确保重构操作没有引入新的错误。
    • 手动测试:如果有必要,进行手动测试以验证功能的正确性。
  4. 代码审查
    • 同行评审:让同事或其他团队成员审查你的更改,确保代码质量和可维护性没有下降。
    • 文档更新:如果项目有维护文档的习惯,记得更新相关文档,说明内联临时变量的影响。

示例

假设有一个方法 calculateTotal,其中包含一个不必要的临时变量,我们希望对其进行“内联临时变量”的重构:

public class Order {
   private double price;
   private int quantity;
   private double taxRate;

   public double calculateTotal() {
      double subTotal = price * quantity;
      double tax = subTotal * taxRate;
      return subTotal + tax;
   }
}

步骤如下:

  1. 识别需要内联的临时变量:
    • 临时变量 subTotaltax 只被使用一次,且表达式简单。
  2. 替换临时变量:
    • subTotaltax 的使用替换为其赋值表达式:

        public class Order {
         private double price;
         private int quantity;
         private double taxRate;
      
         public double calculateTotal() {
            return (price * quantity) + (price * quantity * taxRate);
         }
      }
      
  3. 测试:
    • 编译代码:确保代码编译通过,没有任何语法错误。
    • 运行测试:运行所有相关的单元测试,确保重构操作没有引入新的错误。
  4. 代码审查:
    • 让同事审查代码,确保没有引入新的问题。

练习

基础练习题

  1. 内联简单临时变量
    • 给定以下 Java 代码,processUserInput方法中有一个不必要的临时变量。请将其内联。

        public class UserProcessor {
         private String birthYearInput;
      
         public UserProcessor(String birthYearInput) {
            this.birthYearInput = birthYearInput;
         }
      
         public void processUserInput() {
            int age = 2025 - Integer.parseInt(birthYearInput);
            System.out.println("User's age is: " + age);
            if (age >= 18) {
               System.out.println("User is an adult.");
            } else {
               System.out.println("User is a minor.");
            }
         }
      }
      
  2. 内联重复使用的临时变量
    • 下面的 Java 代码中有两个方法calculateRectangleArea和calculateSquareArea,都包含一个不必要的临时变量。请将其内联。

        public class ShapeCalculator {
         public void calculateRectangleArea(int length, int width) {
            System.out.println("Rectangle area is: " + (length * width));
         }
      
         public void calculateSquareArea(int side) {
            System.out.println("Square area is: " + (side * side));
         }
      }
      

进阶练习题

  1. 内联复杂表达式中的临时变量
    • 在这段 Java 代码中,calculateShippingCost方法内有一个不必要的临时变量。请将其内联。

        public class OrderShipping {
         private double baseShippingCost;
         private int orderQuantity;
         private double discountRate;
      
         public OrderShipping(double baseShippingCost, int orderQuantity, double discountRate) {
            this.baseShippingCost = baseShippingCost;
            this.orderQuantity = orderQuantity;
            this.discountRate = discountRate;
         }
      
         public double calculateShippingCost() {
            return baseShippingCost - (baseShippingCost * discountRate) - (orderQuantity > 5 ? 5 : 0);
         }
      }
      
  2. 内联方法与返回值处理
    • 给定以下 Java 代码,processData方法包含一个不必要的临时变量。请将其内联。

        import java.util.ArrayList;
      import java.util.List;
      
      public class DataProcessor {
         public int processData(int[] dataArray) {
            List<Integer> processedData = new ArrayList<>();
            for (int num : dataArray) {
               num = num * 2;
               if (num > 10) {
                  num = num - 5;
               }
               processedData.add(num);
            }
            int sum = 0;
            for (int num : processedData) {
               sum += num;
            }
            return sum;
         }
      }
      

综合拓展练习题

  1. 多模块内联与代码审查模拟
    • 考虑一个简单的 Java 电商系统,有Product类、Cart类和Order类。Cart类中的calculateCartTotal方法和Order类中的calculateOrderTotal方法都有不必要的临时变量,同时Cart类中的applyCartDiscount方法也有不必要的临时变量。

    • 请对这些方法进行 “内联临时变量” 重构,将不必要的临时变量内联。

    • 假设你完成了重构,请模拟一份简单的代码审查报告,指出重构后的优点和可能存在的潜在问题。

        class Product {
         private double price;
      
         public Product(double price) {
            this.price = price;
         }
      
         public double getPrice() {
            return price;
         }
      }
      
      class Cart {
         private Product[] products;
         private double discountRate;
      
         public Cart(Product[] products, double discountRate) {
            this.products = products;
            this.discountRate = discountRate;
         }
      
         public double calculateCartTotal() {
            double total = 0;
            for (Product product : products) {
               total += product.getPrice();
            }
            return total - (total * discountRate);
         }
      
         public void applyCartDiscount() {
            if (products.length > 3) {
               discountRate += 0.05;
            }
            if (calculateCartTotal() > 100) {
               discountRate += 0.1;
            }
         }
      }
      
      class Order {
         private Product[] products;
         private double shippingCost;
      
         public Order(Product[] products, double shippingCost) {
            this.products = products;
            this.shippingCost = shippingCost;
         }
      
         public double calculateOrderTotal() {
            double total = 0;
            for (Product product : products) {
               total += product.getPrice();
            }
            return total + shippingCost;
         }
      }