檢視程式碼重構情境與 GitHub Copilot 最佳實務

已完成

重構程式碼是重組現有程式碼的過程,而不改變其行為。 重構的優點包括改善程式碼可讀性、降低複雜度、讓程式代碼更容易維護,以及讓新功能更容易新增。 實施 GitHub Copilot 最佳實務能幫助你更有效率地工作並獲得更好的成果。

GitHub Copilot 最佳實務

GitHub Copilot 是一個強大的工具,可以幫助你重構並改進你的程式碼。 不過,為了獲得最佳效果,使用GitHub Copilot時應該遵循一些最佳實務。

使用更好的提示改善回應

你可以透過撰寫更有效的提示來提升 GitHub Copilot 回應的品質。 精心設計的提示詞能幫助 GitHub 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.
    
  • 將複雜工作分解成更簡單的工作。

    與其要求 GitHub 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 變數來指稱整個程式碼基礎:「資料庫連接字串在程式碼基礎中的哪裡被使用?」

  • 逐一查看提示。

    提供後續提示以精簡或修改回應。

    例如,如果您從下列提示開始:

    「撰寫函式來計算數位的因數」。

    您可以追蹤:

    「請勿使用遞迴,並使用快取來最佳化。」

    然後:

    「使用有意義的變數名稱」。

  • 讓聊天記錄保持相關。

    GitHub Copilot 利用對話的歷史來提供背景資訊。 如果過去的問題和回應不相關,請從歷程記錄中移除。 或者,如果您想要變更內容,請啟動新的工作階段。

    當上下文視窗填滿時,Visual Studio Code 會自動壓縮對話歷史。 你也可以隨時使用這個 /compact 指令手動摘要對話內容,並釋放上下文空間。 聊天輸入框中的上下文視窗控制顯示目前使用情況。

提供正確的內容和工具

使用相關內容豐富您的提示,以在聊天中取得更精確且相關的回應。 使用正確的工具,您可以提升開發人員生產力。

  • 在代理程式中,選擇工具按鈕來設定你想使用的工具,或明確地將它們加入你的提示詞中。

  • 使用 #codebase,GitHub Copilot 透過程式碼搜尋自動找到正確的檔案。

  • 使用 #fetch 工具從網頁擷取內容,或使用 #githubRepo 對GitHub倉庫進行程式碼搜尋。

  • 使用 #<file name>#<folder name>#<symbol>,在提示字元中參考檔案、資料夾或符號。

  • 將檔案、資料夾或編輯器索引標籤放到聊天提示中。

  • 將問題、測試失敗或終端機輸出加入到聊天提示中,以取得具體情境內容。

備註

當你使用代理程式時,GitHub Copilot 會自動為你找到相關的檔案和上下文。

常見的程式代碼重構案例

GitHub Copilot 能以多種方式幫助你快速重構程式碼。 下列清單包含一些重構程式代碼的常見案例:

  • 優化效率不佳的程序代碼
  • 清除重複的程序代碼
  • 讓程式代碼更簡潔
  • 分割複雜程式代碼單位
  • 重寫條件式程式代碼以提升可讀性
  • 重新格式化程序代碼以使用不同的結構

使用 GitHub Copilot 來優化低效率的程式碼

GitHub 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 讓程式碼更精簡

如果程式代碼過於冗長,可能會難以閱讀和維護。 GitHub 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 來拆分複雜的程式碼單元

執行多個作業的大型方法或函式,重複使用的機會可能少於著重於執行特定作業的小型簡單函式。 它們可能也比較難以理解和偵錯。

GitHub 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)

你可以用 GitHub 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方法使用一系列ifelse 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);
}

如果你的程式碼標準要求函式用箭頭表示,參數用描述性名稱,你可以用 GitHub 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 可以協助你以多種方式重構程式碼。 你可以用聊天視窗或內嵌聊天,請 GitHub Copilot 優化低效率程式碼、清理重複程式碼、讓程式碼更簡潔、拆分複雜程式碼單元、重寫條件碼以提升可讀性,以及重新格式化程式碼以使用不同結構。