# 提高代码可读性和可维护性

副驾驶聊天 可以建议使代码更易于理解和维护的方法。

可读性差的代码对于其他开发人员来说很难维护和扩展。 副驾驶聊天 可以通过多种方式提供帮助。 例如，通过：

* [建议改进变量名称](#improving-variable-names)
* [避免顺序条件检查](#avoiding-sequential-conditional-checks)
* [减少嵌套逻辑](#reducing-nested-logic)
* [将大型方法拆分为更小、更易读的方法](#splitting-up-large-methods)

记录代码是提高代码可维护性的另一种方法。 有关使用 副驾驶聊天 帮助向代码添加有用注释的信息，请参阅[记录代码](/zh/copilot/copilot-chat-cookbook/documenting-code)中的示例提示。

> \[!NOTE] 本文中显示的响应是示例。 副驾驶聊天 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。

## 改进变量名称

描述性变量名称和参数名称可让人更容易理解其用途。

### 示例方案

此 JavaScript 代码将有关人员年龄的消息记录到控制台。 抽象的参数名称让人难以理解代码的用途。

```javascript id=log-persons-age
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 copy prompt ref=log-persons-age
Improve the variable names in this function
```

### 示例响应

Copilot 建议描述性变量名称。

```javascript
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 代码输出各种动物发出的声音（如果已定义）或“未知动物”（如果无法识别动物类型）。 但是，`if...else` 语句链使代码效率低下且繁琐。

```python id=animal-sound
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 copy prompt ref=animal-sound
Simplify this code. Avoid using if/else chains but retain all function return values.
```

### 示例响应

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

```python
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` 语句会使代码变得过于复杂。

```ruby id=determine-access
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 copy prompt ref=determine-access
Rewrite this code to avoid the nested if/else statements
```

### 示例响应

Copilot 建议使用 guard 子句提前处理条件并返回相应的消息。

```ruby
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 方法处理客户订单并输出消息。 它在单个方法中执行多个任务。

```java id=process-order
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 copy prompt ref=process-order
How could the processOrder method be refactored to be more useful and easier to maintain
```

### 示例响应

Copilot 建议将此方法分解为更小、更有针对性的方法。

```java
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);
}
```

## 其他阅读材料

* [GitHub Copilot 对话助手的提示设计](/zh/copilot/using-github-copilot/prompt-engineering-for-github-copilot)
* [使用 GitHub Copilot 的最佳做法](/zh/copilot/using-github-copilot/best-practices-for-using-github-copilot)