코드 리팩터링 시나리오 및 GitHub Copilot 모범 사례 검토

Completed

코드 리팩터링은 동작을 변경하지 않고 기존 코드를 재구성하는 프로세스입니다. 리팩터링의 이점에는 코드 가독성 향상, 복잡성 감소, 더 간편한 코드 유지 관리 및 보다 쉬운 새 기능 추가 등이 있습니다. 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 변수를 사용하여 전체 코드베이스를 참조합니다. "데이터베이스 연결 문자열이 #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 메서드는 일련의 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);
}

코딩 표준에서 함수에 화살표 표기법과 매개 변수에 대한 설명이 포함된 이름을 사용해야 하는 경우 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 비효율적인 코드를 최적화하고, 반복되는 코드를 정리하고, 코드를 더 간결하게 만들고, 복잡한 코드 단위를 분할하고, 조건부 코드를 다시 작성하여 가독성을 높이고, 코드를 다시 포맷하여 다른 구조를 사용하도록 요청할 수 있습니다.