跳至主要内容

提升代码可读性和可维护性

Copilot Chat 可以提供让代码更易理解和维护的建议。

可读性差的代码让其他开发者难以维护和扩展。Copilot Chat 可以通过多种方式提供帮助,例如,

为代码添加文档是提升代码可维护性的另一种方式。有关如何使用 Copilot Chat 为代码添加有用注释的信息,请参阅 记录代码 中的示例提示。

注意

本文中显示的响应为示例。Copilot Chat 的响应是非确定性的,因此您可能会得到与此处显示不同的响应。

改进变量命名

具有描述性的变量名和参数名可以让人更容易理解它们的用途。

示例情景

下面的 JavaScript 代码将在控制台记录一条关于某人年龄的消息。抽象的参数名导致代码意义难以理解。

function logPersonsAge(a, b, c) {
  if (c) {
    console.log(a + " is " + b + " years old.");
  } else {
    console.log(a + " does not want to reveal their age.");
  }
}

示例提示

在编辑器中,选中你想要修改的函数,然后向 Copilot Chat 提问

Copilot 提示
Improve the variable names in this function

示例回复

Copilot 建议使用更具描述性的变量名。

function logPersonAge(name, age, revealAge) {
  if (revealAge) {
    console.log(name + " is " + age + " years old.");
  } else {
    console.log(name + " does not want to reveal their age.");
  }
}

避免顺序条件检查

if...else 链条可能难以阅读,尤其是当链条很长时。

示例情景

下面的 Python 代码会打印各种动物的叫声(如果已定义),否则打印 “Unknown animal”。然而,if...else 链导致代码效率低下且难以维护。

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Bird(Animal):
    def speak(self):
        return "Tweet!"

def animal_sound(animal_type):
    if animal_type == "dog":
        return Dog().speak()
    elif animal_type == "cat":
        return Cat().speak()
    elif animal_type == "bird":
        return Bird().speak()
    else:
        return "Unknown animal"

print(animal_sound("dog"))
print(animal_sound("cat"))
print(animal_sound("bird"))
print(animal_sound("fish"))

示例提示

Copilot 提示
Simplify this code. Avoid using if/else chains but retain all function return values.

示例回复

Copilot 建议使用字典将动物类型映射到相应的类。

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Bird(Animal):
    def speak(self):
        return "Tweet!"

def animal_sound(animal_type):
    animals = {
        "dog": Dog,
        "cat": Cat,
        "bird": Bird
    }
    animal_class = animals.get(animal_type, Animal)
    return animal_class().speak() if animal_class != Animal else "Unknown animal"

print(animal_sound("dog"))
print(animal_sound("cat"))
print(animal_sound("bird"))
print(animal_sound("fish"))

减少嵌套逻辑

深度嵌套的结构会让代码难以跟踪,从而导致将来修改或扩展代码逻辑变得困难。

示例情景

下面的 Ruby 代码根据三个参数打印用户账户信息。使用嵌套的 if...else 语句使代码显得不必要地复杂。

def determine_access(user_role, has_permission, is_active)
  if user_role == "admin"
    if has_permission
      if is_active
        "Active admin account with full access."
      else
        "Inactive admin account."
      end
    else
      "Admin account lacks necessary permissions."
    end
  else
    "Access denied."
  end
end

puts determine_access("admin", true, true)
puts determine_access("admin", true, false)
puts determine_access("admin", false, true)
puts determine_access("user", true, true)

示例提示

Copilot 提示
Rewrite this code to avoid the nested if/else statements

示例回复

Copilot 建议使用守卫子句(guard clause)在早期处理条件并返回相应的消息。

def determine_access(user_role, has_permission, is_active)
  return "Access denied." unless user_role == "admin"
  return "Admin account lacks necessary permissions." unless has_permission
  return "Inactive admin account." unless is_active

  "Active admin account with full access."
end

puts determine_access("admin", true, true)
puts determine_access("admin", true, false)
puts determine_access("admin", false, true)
puts determine_access("user", true, true)

拆分大型方法

如果方法或函数过长,往往难以把握其具体作用,从而增加维护难度。执行多个任务的方法或函数在其他场景下可能无法复用,同时也不易对各个任务进行单独测试。

示例情景

下面的 Java 方法处理客户订单并打印信息。它在单个方法中完成了多个任务。

public void processOrder(Order order) {
  if (order == null || order.getItems().isEmpty()) {
    throw new IllegalArgumentException("Order is invalid.");
  }

  double totalPrice = 0.0;
  for (Item item : order.getItems()) {
    totalPrice += item.getPrice() * item.getQuantity();
  }
  order.setTotalPrice(totalPrice);

  if (totalPrice > 0) {
    order.setStatus("Processed");
  } else {
    order.setStatus("Pending");
  }

  System.out.println("Order for customer " + order.getCustomerName() + " has been processed. Total price: " + totalPrice);
}

示例提示

Copilot 提示
How could the processOrder method be refactored to be more useful and easier to maintain

示例回复

Copilot 建议将此方法拆分为更小、更专注的子方法。

public void processOrder(Order order) {
    validateOrder(order);
    double totalPrice = calculateTotalPrice(order);
    updateOrderStatus(order, totalPrice);
    printOrderSummary(order, totalPrice);
}

private void validateOrder(Order order) {
    if (order == null || order.getItems().isEmpty()) {
        throw new IllegalArgumentException("Order is invalid.");
    }
}

private double calculateTotalPrice(Order order) {
    double totalPrice = 0.0;
    for (Item item : order.getItems()) {
        totalPrice += item.getPrice() * item.getQuantity();
    }
    order.setTotalPrice(totalPrice);
    return totalPrice;
}

private void updateOrderStatus(Order order, double totalPrice) {
    if (totalPrice > 0) {
        order.setStatus("Processed");
    } else {
        order.setStatus("Pending");
    }
}

private void printOrderSummary(Order order, double totalPrice) {
    System.out.println("Order for customer " + order.getCustomerName() + " has been processed. Total price: " + totalPrice);
}

延伸阅读

© . This site is unofficial and not affiliated with GitHub, Inc.