• Code Bloaters-代码肿胀


    Code Bloaters

    1. Long Method

    1.1 method lines cant longer then ten should make you start asking questions.

    # Extract Method

    Problem

    //You have a code fragment that can be grouped together.
    void printOwing() {
      printBanner();
    
      // Print details.
      System.out.println("name: " + name);
      System.out.println("amount: " + getOutstanding());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Solution

    //Move this code to a separate new method (or function) and replace the old code with a call to the method.
    void printOwing() {
      printBanner();
      printDetails(getOutstanding());
    }
    
    void printDetails(double outstanding) {
      System.out.println("name: " + name);
      System.out.println("amount: " + outstanding);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    # Replace Temp with Query

    Problem

    //You place the result of an expression in a local variable for later use in your code.
    double calculateTotal() {
      double basePrice = quantity * itemPrice;
      if (basePrice > 1000) {
        return basePrice * 0.95;
      }
      else {
        return basePrice * 0.98;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Solution

    //Move the entire expression to a separate method and return the result from it. Query the method instead of using a variable. Incorporate the new method in other methods, if necessary.
    double calculateTotal() {
      if (basePrice() > 1000) {
        return basePrice() * 0.95;
      }
      else {
        return basePrice() * 0.98;
      }
    }
    double basePrice() {
      return quantity * itemPrice;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    # Introduce Parameter Object

    在这里插入图片描述

    # PreServe Whole Object

    Problem

    //You get several values from an object and then pass them as parameters to a method.
    int low = daysTempRange.getLow();
    int high = daysTempRange.getHigh();
    boolean withinPlan = plan.withinRange(low, high);
    
    • 1
    • 2
    • 3
    • 4

    Solution

    //Instead, try passing the whole object.
    boolean withinPlan = plan.withinRange(daysTempRange);
    
    • 1
    • 2

    # Replace Method with Method Object

    Problem

    //You have a long method in which the local variables are so intertwined that you cannot apply Extract Method.
    class Order {
      // ...
      public double price() {
        double primaryBasePrice;
        double secondaryBasePrice;
        double tertiaryBasePrice;
        // Perform long computation.
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Solution

    //Transform the method into a separate class so that the local variables become fields of the class. Then you can split the method into several methods within the same class.
    class Order {
      // ...
      public double price() {
        return new PriceCalculator(this).compute();
      }
    }
    
    class PriceCalculator {
      private double primaryBasePrice;
      private double secondaryBasePrice;
      private double tertiaryBasePrice;
      
      public PriceCalculator(Order order) {
        // Copy relevant information from the
        // order object.
      }
      
      public double compute() {
        // Perform long computation.
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    # Decompose Conditional

    Problem

    //You have a complex conditional (if-then/else or switch).
    if (date.before(SUMMER_START) || date.after(SUMMER_END)) {
      charge = quantity * winterRate + winterServiceCharge;
    }
    else {
      charge = quantity * summerRate;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Solution

    //Decompose the complicated parts of the conditional into separate methods: the condition, then and else.
    if (isSummer(date)) {
      charge = summerCharge(quantity);
    }
    else {
      charge = winterCharge(quantity);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.2 write code is easier than read code, so you must let other know what method do

    //Using Descriptive method name
    public void removeUserInfo()
    public void checkUserInfoEligible()
    
    • 1
    • 2
    • 3

    2. Large Class

    A class contains many fields/methods/lines of code.

    # Extract Class
    在这里插入图片描述
    *** # Extract Subclass***

    Problem
    A class has features that are used only in certain cases.
    在这里插入图片描述
    Solution
    Create a subclass and use it in these cases.
    在这里插入图片描述

    # Extract Interface

    Problem
    Multiple clients are using the same part of a class interface. Another case: part of the interface in two classes is the same.
    在这里插入图片描述

    Solution
    在这里插入图片描述

    # Duplicate Observed Data

    Problem
    Is domain data stored in classes responsible for the GUI?
    在这里插入图片描述

    Solution
    Then it is a good idea to separate the data into separate classes, ensuring connection and synchronization between the domain class and the GUI.
    在这里插入图片描述

    3. Primitive Obsession

    # Replace type code with class

    Problem
    A class has a field that contains type code. The values of this type are not used in operator conditions and do not affect the behavior of the program.
    在这里插入图片描述

    Solution
    Create a new class and use its objects instead of the type code values.
    在这里插入图片描述

    # Replace type code with subclass

    Problem
    You have a coded type that directly affects program behavior (values of this field trigger various code in conditionals).
    在这里插入图片描述
    Solution
    Create subclasses for each value of the coded type. Then extract the relevant behaviors from the original class to these subclasses. Replace the control flow code with polymorphism.
    在这里插入图片描述
    # Replace Type Code with State/Strategy

    Problem
    You have a coded type that affects behavior but you cannot use subclasses to get rid of it.
    在这里插入图片描述
    Solution
    Replace type code with a state object. If it is necessary to replace a field value with type code, another state object is “plugged in”.
    在这里插入图片描述

    # Replace Array with Object

    Problem
    You have an array that contains various types of data.

    String[] row = new String[2];
    row[0] = "Liverpool";
    row[1] = "15";
    
    • 1
    • 2
    • 3

    Solution
    Replace the array with an object that will have separate fields for each element.

    Performance row = new Performance();
    row.setName("Liverpool");
    row.setWins("15");
    
    • 1
    • 2
    • 3

    4. Long Parameter List

    # Replace Parameter with method call

    Problem
    Before a method call, a second method is run and its result is sent back to the first method as an argument. But the parameter value could have been obtained inside the method being called.

    int basePrice = quantity * itemPrice;
    double seasonDiscount = this.getSeasonalDiscount();
    double fees = this.getFees();
    double finalPrice = discountedPrice(basePrice, seasonDiscount, fees);
    
    • 1
    • 2
    • 3
    • 4

    Solution
    Instead of passing the value through a parameter, place the value-getting code inside the method.

    int basePrice = quantity * itemPrice;
    double finalPrice = discountedPrice(basePrice);
    
    • 1
    • 2

    # Preserve Whole Object

    Problem
    You get several values from an object and then pass them as parameters to a method.

    int low = daysTempRange.getLow();
    int high = daysTempRange.getHigh();
    boolean withinPlan = plan.withinRange(low, high);
    
    • 1
    • 2
    • 3

    Solution
    Instead, try passing the whole object.

    boolean withinPlan = plan.withinRange(daysTempRange);
    
    • 1

    # Introduce Parameter Object

    Problem
    Your methods contain a repeating group of parameters.
    在这里插入图片描述

    Solution
    Replace these parameters with an object.
    在这里插入图片描述

    5. Data Clumps

    pls refer to Extract Class, Introduce Parameter Object, Preserve Whole Object

  • 相关阅读:
    健身耳机哪些品牌好?健身运动耳机推荐
    35岁危机来临前,程序员如何未雨绸缪?
    基于SkeyeVSS系统实现政府综合性视频监控平台管理解决方案
    Redis应用场景
    nvm常用命令有哪些?nvm如何切换node版本?nvm如何下载node?nvm安装包
    MySQL——数据类型
    <2>【深度学习 × PyTorch】pandas | 数据预处理 | 处理缺失值:插值法 | networkx模块绘制知识图谱 | 线性代数初步
    求程序段中++x或者x++的频度,时间复杂度、执行次数
    一套有趣的期权套利题目
    海康相机SDK二次开发的一些报错和解决办法
  • 原文地址:https://blog.csdn.net/Stephen_mu/article/details/125461325