{"meta":{"title":"提高代码可读性和可维护性","intro":"副驾驶聊天 可以建议使代码更易于理解和维护的方法。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook","title":"GitHub Copilot Chat 指南"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/refactor-code","title":"重构代码"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/refactor-code/improve-code-readability","title":"提高代码可读性"}],"documentType":"article"},"body":"# 提高代码可读性和可维护性\n\n副驾驶聊天 可以建议使代码更易于理解和维护的方法。\n\n可读性差的代码对于其他开发人员来说很难维护和扩展。 副驾驶聊天 可以通过多种方式提供帮助。 例如，通过：\n\n* [建议改进变量名称](#improving-variable-names)\n* [避免顺序条件检查](#avoiding-sequential-conditional-checks)\n* [减少嵌套逻辑](#reducing-nested-logic)\n* [将大型方法拆分为更小、更易读的方法](#splitting-up-large-methods)\n\n记录代码是提高代码可维护性的另一种方法。 有关使用 副驾驶聊天 帮助向代码添加有用注释的信息，请参阅[记录代码](/zh/copilot/copilot-chat-cookbook/documenting-code)中的示例提示。\n\n> \\[!NOTE] 本文中显示的响应是示例。 副驾驶聊天 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\n\n## 改进变量名称\n\n描述性变量名称和参数名称可让人更容易理解其用途。\n\n### 示例方案\n\n此 JavaScript 代码将有关人员年龄的消息记录到控制台。 抽象的参数名称让人难以理解代码的用途。\n\n```javascript id=log-persons-age\nfunction logPersonsAge(a, b, c) {\n  if (c) {\n    console.log(a + \" is \" + b + \" years old.\");\n  } else {\n    console.log(a + \" does not want to reveal their age.\");\n  }\n}\n```\n\n### 示例提示\n\n在编辑器中，选择要更改的函数，然后让 副驾驶聊天 完成以下操作：\n\n```copilot copy prompt ref=log-persons-age\nImprove the variable names in this function\n```\n\n### 示例响应\n\nCopilot 建议描述性变量名称。\n\n```javascript\nfunction logPersonAge(name, age, revealAge) {\n  if (revealAge) {\n    console.log(name + \" is \" + age + \" years old.\");\n  } else {\n    console.log(name + \" does not want to reveal their age.\");\n  }\n}\n```\n\n## 避免连贯条件检查\n\n```\n          `if...else` 链难以读取，尤其是在链很长的时候。\n```\n\n### 示例方案\n\n此 Python 代码输出各种动物发出的声音（如果已定义）或“未知动物”（如果无法识别动物类型）。 但是，`if...else` 语句链使代码效率低下且繁琐。\n\n```python id=animal-sound\nclass Animal:\n    def speak(self):\n        pass\n\nclass Dog(Animal):\n    def speak(self):\n        return \"Woof!\"\n\nclass Cat(Animal):\n    def speak(self):\n        return \"Meow!\"\n\nclass Bird(Animal):\n    def speak(self):\n        return \"Tweet!\"\n\ndef animal_sound(animal_type):\n    if animal_type == \"dog\":\n        return Dog().speak()\n    elif animal_type == \"cat\":\n        return Cat().speak()\n    elif animal_type == \"bird\":\n        return Bird().speak()\n    else:\n        return \"Unknown animal\"\n\nprint(animal_sound(\"dog\"))\nprint(animal_sound(\"cat\"))\nprint(animal_sound(\"bird\"))\nprint(animal_sound(\"fish\"))\n```\n\n### 示例提示\n\n```copilot copy prompt ref=animal-sound\nSimplify this code. Avoid using if/else chains but retain all function return values.\n```\n\n### 示例响应\n\nCopilot 建议使用字典将动物类型映射到相应的类别。\n\n```python\nclass Animal:\n    def speak(self):\n        pass\n\nclass Dog(Animal):\n    def speak(self):\n        return \"Woof!\"\n\nclass Cat(Animal):\n    def speak(self):\n        return \"Meow!\"\n\nclass Bird(Animal):\n    def speak(self):\n        return \"Tweet!\"\n\ndef animal_sound(animal_type):\n    animals = {\n        \"dog\": Dog,\n        \"cat\": Cat,\n        \"bird\": Bird\n    }\n    animal_class = animals.get(animal_type, Animal)\n    return animal_class().speak() if animal_class != Animal else \"Unknown animal\"\n\nprint(animal_sound(\"dog\"))\nprint(animal_sound(\"cat\"))\nprint(animal_sound(\"bird\"))\nprint(animal_sound(\"fish\"))\n```\n\n## 减少嵌套逻辑\n\n深度嵌套的结构会使代码难以理解，从而难以在将来修改或扩展代码的逻辑。\n\n### 示例方案\n\n此 Ruby 代码基于三个参数输出有关用户帐户的信息。 使用嵌套 `if...else` 语句会使代码变得过于复杂。\n\n```ruby id=determine-access\ndef determine_access(user_role, has_permission, is_active)\n  if user_role == \"admin\"\n    if has_permission\n      if is_active\n        \"Active admin account with full access.\"\n      else\n        \"Inactive admin account.\"\n      end\n    else\n      \"Admin account lacks necessary permissions.\"\n    end\n  else\n    \"Access denied.\"\n  end\nend\n\nputs determine_access(\"admin\", true, true)\nputs determine_access(\"admin\", true, false)\nputs determine_access(\"admin\", false, true)\nputs determine_access(\"user\", true, true)\n```\n\n### 示例提示\n\n```copilot copy prompt ref=determine-access\nRewrite this code to avoid the nested if/else statements\n```\n\n### 示例响应\n\nCopilot 建议使用 guard 子句提前处理条件并返回相应的消息。\n\n```ruby\ndef determine_access(user_role, has_permission, is_active)\n  return \"Access denied.\" unless user_role == \"admin\"\n  return \"Admin account lacks necessary permissions.\" unless has_permission\n  return \"Inactive admin account.\" unless is_active\n\n  \"Active admin account with full access.\"\nend\n\nputs determine_access(\"admin\", true, true)\nputs determine_access(\"admin\", true, false)\nputs determine_access(\"admin\", false, true)\nputs determine_access(\"user\", true, true)\n```\n\n## 拆分大型方法\n\n如果方法或函数太长，可能很难准确掌握其作用，从而难以维护。 执行多项任务的方法或函数可能无法在其他上下文中重复使用。 单独测试每个任务也可能很困难。\n\n### 示例方案\n\n此 Java 方法处理客户订单并输出消息。 它在单个方法中执行多个任务。\n\n```java id=process-order\npublic void processOrder(Order order) {\n  if (order == null || order.getItems().isEmpty()) {\n    throw new IllegalArgumentException(\"Order is invalid.\");\n  }\n\n  double totalPrice = 0.0;\n  for (Item item : order.getItems()) {\n    totalPrice += item.getPrice() * item.getQuantity();\n  }\n  order.setTotalPrice(totalPrice);\n\n  if (totalPrice > 0) {\n    order.setStatus(\"Processed\");\n  } else {\n    order.setStatus(\"Pending\");\n  }\n\n  System.out.println(\"Order for customer \" + order.getCustomerName() + \" has been processed. Total price: \" + totalPrice);\n}\n```\n\n### 示例提示\n\n```copilot copy prompt ref=process-order\nHow could the processOrder method be refactored to be more useful and easier to maintain\n```\n\n### 示例响应\n\nCopilot 建议将此方法分解为更小、更有针对性的方法。\n\n```java\npublic void processOrder(Order order) {\n    validateOrder(order);\n    double totalPrice = calculateTotalPrice(order);\n    updateOrderStatus(order, totalPrice);\n    printOrderSummary(order, totalPrice);\n}\n\nprivate void validateOrder(Order order) {\n    if (order == null || order.getItems().isEmpty()) {\n        throw new IllegalArgumentException(\"Order is invalid.\");\n    }\n}\n\nprivate double calculateTotalPrice(Order order) {\n    double totalPrice = 0.0;\n    for (Item item : order.getItems()) {\n        totalPrice += item.getPrice() * item.getQuantity();\n    }\n    order.setTotalPrice(totalPrice);\n    return totalPrice;\n}\n\nprivate void updateOrderStatus(Order order, double totalPrice) {\n    if (totalPrice > 0) {\n        order.setStatus(\"Processed\");\n    } else {\n        order.setStatus(\"Pending\");\n    }\n}\n\nprivate void printOrderSummary(Order order, double totalPrice) {\n    System.out.println(\"Order for customer \" + order.getCustomerName() + \" has been processed. Total price: \" + totalPrice);\n}\n```\n\n## 其他阅读材料\n\n* [GitHub Copilot 对话助手的提示设计](/zh/copilot/using-github-copilot/prompt-engineering-for-github-copilot)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/using-github-copilot/best-practices-for-using-github-copilot)"}