查看代码重构方案和 GitHub Copilot 最佳做法
重构代码是重新构建现有代码的过程,而不更改其外部行为的过程。 重构的好处包括提高代码可读性、降低复杂性、使代码更易于维护,并可以更轻松地添加新功能。 实施 GitHub Copilot 最佳做法可帮助你更高效地工作并获得更好的结果。
GitHub Copilot 最佳做法
GitHub Copilot 是一种功能强大的工具,可帮助你重构和改进代码。 但是,若要获得最佳结果,在使用 Copilot 时,应遵循一些最佳做法。
通过更好的提示改进响应
可以通过编写更有效的提示来提高 Copilot 响应的质量。 精心制作的提示可以帮助 Copilot 更好地了解你的要求,并生成更相关的代码建议。
以下准则可帮助你编写更好的提示:
从常规开始,然后再具体化。
Generate a Calculator class. Add methods for addition, subtraction, multiplication, division, and factorial. Don't use any external libraries and don't use recursion.
提供所需内容的示例。
Generate a function that takes a string and returns the number of vowels in it. For example: findVowels("hello") returns 2, findVowels("sky") returns 0.
将复杂任务分解为更简单的任务。
不要要求 Copilot “生成膳食规划器应用”,而是将提示分解为较小的任务。
例如:
Generate a function that takes a list of ingredients and returns a list of recipes.
Generate a function that takes a list of recipes and returns a shopping list.
Generate a function that takes a list of recipes and returns a meal plan for the week.
提供正确的上下文,例如代码选择、文件、终端输出等。
例如,使用
#codebase
变量引用整个代码库:“#codebase 中使用的数据库连接字符串在哪里?”迭代你的提示。
提供后续提示以优化或修改响应。
例如,如果使用以下提示开始:
“编写函数以计算数字的阶乘。
可以跟进:
“不要使用递归并使用缓存进行优化。
然后:
“使用有意义的变量名称。”
保持聊天记录的相关性。
Copilot 使用对话历史记录来提供上下文。 如果这些问题与历史记录无关,请从历史记录中删除过去的问题和回复。 或者,如果要更改上下文,请启动一个新会话。
提供正确的上下文和工具
使用相关上下文丰富提示,以在聊天中获取更准确和相关的响应。 借助正确的工具,你可以提高开发人员的工作效率。
在代理模式下,选择工具按钮以配置要使用的工具,或将其显式添加到您的提示信息中。
用于
#codebase
通过执行代码搜索让 Copilot 自动查找正确的文件。使用该工具
#fetch
从网页中提取内容,或者用于#githubRepo
在 GitHub 存储库上执行代码搜索。在提示中通过使用
#<file name>
、#<folder name>
或#<symbol>
来引用文件、文件夹或符号。将文件、文件夹或编辑器选项卡拖放到聊天提示符上。
将问题、测试失败或终端输出添加到聊天提示中,以了解特定于场景的上下文。
注释
使用代理模式时,Copilot 会自主找到相关的文件和上下文。
常见代码重构方案
GitHub Copilot 可以帮助你以多种方式快速重构代码。 以下列表包括一些用于重构代码的常见方案:
- 优化低效代码
- 清理重复的代码
- 使代码更加简洁
- 拆分复杂的代码单元
- 重写条件代码以提高可读性
- 重新格式化代码以使用其他结构
使用 GitHub Copilot 优化低效代码
Copilot 可以帮助你优化代码。 例如,可以优化代码以使代码运行更快。
请考虑以下 bash 脚本:
#!/bin/bash
# Find all .txt files and count the number of lines in each file
for file in $(find . -type f -name "*.txt"); do
wc -l "$file"
done
可以使用聊天功能来评估用于优化脚本的不同方面的选项,例如性能。
#!/bin/bash
# Find all .txt files and count the number of lines in each file (improved performance)
find . -type f -name "*.txt" -print0 | xargs -0 wc -l
使用 GitHub Copilot 清理重复的代码
避免重复将使代码更易于修改和调试。 例如,如果在文件中的不同位置多次执行相同的计算,则可以将计算移至函数。
在以下非常简单的 JavaScript 示例中,在两个位置执行相同的计算(商品价格乘以销售的商品数)。
let totalSales = 0;
let applePrice = 3;
let appleSold = 100;
totalSales += applePrice * appleSold;
let orangePrice = 2;
let orangeSold = 50;
totalSales += orangePrice * orangeSold;
console.log(`Total: ${totalSales}`);
可以要求聊天功能将重复计算移动到函数中。
function calculateTotal(price, quantity) {
return price * quantity;
}
let totalSales = 0;
let applePrice = 3;
let appleSold = 100;
totalSales += calculateTotal(applePrice, appleSold);
let orangePrice = 2;
let orangeSold = 50;
totalSales += calculateTotal(orangePrice, orangeSold);
console.log(`Total: ${totalSales}`);
使用 GitHub Copilot 使代码更加简洁
如果代码没必要太冗长,则很难读取和维护。 Copilot 可以建议更简洁版本的所选代码。
以下 Python 代码输出矩形和圆圈的区域,但代码可以更简洁地编写:
def calculate_area_of_rectangle(length, width):
area = length * width
return area
def calculate_area_of_circle(radius):
area = 3.14 * radius * radius
return area
rectangle_length = 5
rectangle_width = 10
rectangle_area = calculate_area_of_rectangle(rectangle_length, rectangle_width)
print(f"Area of rectangle: {rectangle_area}")
circle_radius = 7
circle_area = calculate_area_of_circle(circle_radius)
print(f"Area of circle: {circle_area}")
GitHub Copilot 可以帮助你重构代码并使其更简洁。
def calculate_area_of_rectangle(length, width):
return length * width
def calculate_area_of_circle(radius):
return 3.14 * radius * radius
rectangle_length = 5
rectangle_width = 10
print(f"Area of rectangle: {calculate_area_of_rectangle(rectangle_length, rectangle_width)}")
circle_radius = 7
print(f"Area of circle: {calculate_area_of_circle(circle_radius)}")
使用 GitHub Copilot 拆分复杂代码单元
执行多个操作的大型方法或函数可能比专注于执行特定操作的较小、更简单的函数提供的重用机会更少。 它们还可能更难理解和调试。
Copilot 可以帮助你将复杂代码块拆分为更适合重复使用的较小单元。
下面的 Python 代码是一个非常简单的示例,但它显示了将单个函数拆分为执行特定操作的两个函数的原则。
import pandas as pd
from pandas.io.formats.styler import Styler
def process_data(item, price):
# Cleanse the data
item = item.strip() # Remove leading and trailing whitespace
price = price.strip() # Remove leading and trailing whitespace
price = float(price) # Convert price to a float
# More cleansing operations can be added here
# Create and print a DataFrame
data = {'Item': [item], 'Price': [price]}
df = pd.DataFrame(data)
print(df.to_string(index=False))
# Example usage
item = " Apple "
price = " 1.50 "
process_data(item, price)
可以使用 Copilot 重构代码,以创建用于清理数据、打印数据和处理数据的函数。
import pandas as pd
from pandas.io.formats.styler import Styler
def cleanse_data(item, price):
# Cleanse the data
item = item.strip() # Remove leading and trailing whitespace
price = price.strip() # Remove leading and trailing whitespace
price = float(price) # Convert price to a float
return item, price
def print_data(item, price):
# Create and print a DataFrame
data = {'Item': [item], 'Price': [price]}
df = pd.DataFrame(data)
print(df.to_string(index=False))
def process_data(item, price):
item, price = cleanse_data(item, price)
print_data(item, price)
# Example usage
item = " Apple "
price = " 1.50 "
item, price = cleanse_data(item, price)
print_data(item, price)
使用 GitHub Copilot 重写条件代码以提高可读性
根据不同的条件,通常有几种方法可以编写执行或不执行的代码。 某些条件结构比其他条件结构更适合特定用例,选择替代的条件结构有时会使代码更易于阅读。
此 Java 方法使用一系列 if
和 else if
语句来确定要执行的操作:
public string getSound(String animal) {
if (animal == null) {
System.out.println("Animal is null");
} else if (animal.equalsIgnoreCase("Dog")) {
return "bark";
} else if (animal.equalsIgnoreCase("Cat")) {
return "meow";
} else if (animal.equalsIgnoreCase("Bird")) {
return "tweet";
}
return "unknown";
}
switch 语句可能是应用相同逻辑的更好方法。
/**
* Returns the sound made by the specified animal.
*
* @param animal the name of the animal
* @return the sound made by the animal, or "unknown" if the animal is not recognized
*/
public String getAnimalSound(String animal) {
return switch (animal) {
case null -> "Animal is null";
case "Dog" -> "bark";
case "Cat" -> "meow";
case "Bird" -> "tweet";
default -> "unknown";
};
}
使用 GitHub Copilot 重新格式化代码以使用不同的结构
假设 JavaScript 中有以下函数:
function listRepos(o, p) {
return fetch(`https://api.github.com/orgs/${o}/repos?per_page=${parseInt()}`)
.then(response => response.json())
.then( (data) => data);
}
如果编码标准要求对函数使用箭头表示法和参数的描述性名称,则可以使用 Copilot 来帮助进行这些更改。
const listRepositories = (organization, perPage) => {
return fetch(`https://api.github.com/orgs/${organization}/repos?per_page=${parseInt(perPage)}`)
.then(response => response.json())
.then(data => data);
};
概要
GitHub Copilot 可以帮助你以各种方式重构代码。 可以使用聊天视图或内联聊天来要求 Copilot 优化低效代码、清理重复代码、使代码更加简洁、拆分复杂代码单元、重写条件代码以提高可读性,并重新格式化代码以使用不同的结构。