Skip to main content

GitHub Copilot を使用したコードのリファクタリング

Copilot 人工知能を活用して、コードをすばやく効果的にリファクタリングできます。

はじめに

コードのリファクタリングとは、既存のコードの動作を変更することなく再構築するプロセスです。 リファクタリングの利点には、コードの読みやすさを向上させ、複雑さを軽減し、コードを保守しやすくし、新機能を簡単に追加できるようにすることなどが含まれます。

この記事では、Copilot を使用して IDE でコードをリファクタリングする方法について説明します。

メモ

応答の例は、この記事に含まれています。 GitHub Copilot Chat では、ここに示したものとは異なる応答が返される場合があります。

コードの解釈

既存のコードを変更する前に、その目的と現在どのように動作しているかを理解しておく必要があります。 Copilot は、次のことができるようにします:

  1. IDE のエディターで関連するコードを選択します。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. インライン チャットの入力ボックスに、スラッシュ (/) を入力します。

  4. ドロップダウン リストで [/explain] を選択し、Enter キーを押します。

  5. Copilot が返す説明が数行を超える場合は、[チャットで表示] をクリックすると説明をより読みやすくできます。

非効率的なコードの最適化

Copilot は、コードを最適化するのに役立ちます。例えば、コードをより迅速に実行できます。

コード例

以下の 2 つのセクションでは、次の Bash スクリプトの例を使用して、非効率的なコードを最適化する方法を示します:

#!/bin/bash

# Find all .txt files and count lines in each
for file in $(find . -type f -name "*.txt"); do
    wc -l "$file"
done

Copilot Chat を使用する

Copilot は、Bash スクリプトの例のようにコードを最適化できるかどうかを示します。

  1. for ループまたはファイルの内容全体を選択します。

  2. アクティビティ バーのチャット アイコンをクリックするか、キーボード ショートカットを使用して、Copilot Chat を開きます。

    • VS Code と Visual Studio: Control+Command+i (Mac) / Ctrl+Alt+i (Windows/Linux)
    • JetBrains: Control+Shift+c
  3. チャット パネルの下部にある入力ボックスに、次のように入力します: Can this script be improved?

    Copilot は、コードをより効率的にするための提案で応答します。

  4. 推奨される変更を適用するには:

    • VS Code と JetBrains では: チャット パネルで提案にカーソルを合わせ、[カーソル位置で挿入] のアイコンをクリックします。

      Copilot Chat パネルにある [Insert at cursor] のアイコンのスクリーンショット。

    • Visual Studio では: [プレビュー] をクリックし、比較ビューで [承諾] をクリックします。

Copilot インライン チャットを使用する

または、Bash スクリプトの例のような既存のコードが非効率的であることが既にわかっている場合は、次のようにします:

  1. for ループまたはファイルの内容全体を選択します。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. optimize」と入力して Enter キーを押します。

    Copilot は、修正されたコードを提案します。 次に例を示します。

    find . -type f -name "*.txt" -exec wc -l {} +
    

    これは、この記事で前に示した元のコードよりも効率的です。-exec ... + を使用すれば、find は検出された *.txt ファイルごとに wc を 1 回呼び出すのではなく、使用して複数のファイルを一度に wc に渡すことができます。

  4. Copilot の提案を評価し、変更に同意する場合は、次の手順を実行します:

    • VS Code および Visual Studio では: [承諾] をクリックします。
    • JetBrains: プレビュー アイコン (二重矢印) をクリックし、[すべての差分の適用] アイコン (二重山かっこ) をクリックします。

すべての Copilot の提案と同様に、修正されたコードがエラーなしで実行され、正しい結果が生成されることを常に確認する必要があります。

繰り返しコードをクリーンアップする

繰り返しを回避すると、コードの修正とデバッグが容易になります。 たとえば、同じ計算がファイル内の異なる場所で複数回実行される場合は、計算を関数に移動できます。

次の非常に単純な JavaScript の例では、同じ計算 (商品価格に販売数を掛けたもの) が 2 か所で実行されます。

let totalSales = 0;

let applePrice = 3;
let applesSold = 100;
totalSales += applePrice * applesSold;

let orangePrice = 5;
let orangesSold = 50;
totalSales += orangePrice * orangesSold;

console.log(`Total: ${totalSales}`);

Copilot に、繰り返し計算を関数に移動するように依頼できます。

  1. ファイルのコンテンツ全体を選択します。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. move repeated calculations into functions」と入力して Enter キーを押します。

    Copilot は、修正されたコードを提案します。 次に例を示します。

    function calculateSales(price, quantity) {
      return price * quantity;
    }
    
    let totalSales = 0;
    
    let applePrice = 3;
    let applesSold = 100;
    totalSales += calculateSales(applePrice, applesSold);
    
    let orangePrice = 5;
    let orangesSold = 50;
    totalSales += calculateSales(orangePrice, orangesSold);
    
    console.log(`Total: ${totalSales}`);
    
  4. Copilot の提案を評価し、変更に同意する場合は、次の手順を実行します:

    • VS Code および Visual Studio では: [承諾] をクリックします。
    • JetBrains: プレビュー アイコン (二重矢印) をクリックし、[すべての差分の適用] アイコン (二重山かっこ) をクリックします。

すべての Copilot の提案と同様に、修正されたコードがエラーなしで実行され、正しい結果が生成されることを常に確認する必要があります。

コードの簡潔化

コードが不必要に冗長な場合、読み取りと保守が困難になる可能性があります。 Copilot は、選択したコードのより簡潔なバージョンを提案できます。

次の例では、この Python コードは四角形と円の領域を出力しますが、より簡潔に記述できます:

def calculate_area_of_rectangle(length, width):
    area = length * width
    return area

def calculate_area_of_circle(radius):
    import math
    area = math.pi * (radius ** 2)
    return area

length_of_rectangle = 10
width_of_rectangle = 5
area_of_rectangle = calculate_area_of_rectangle(length_of_rectangle, width_of_rectangle)
print(f"Area of rectangle: {area_of_rectangle}")

radius_of_circle = 7
area_of_circle = calculate_area_of_circle(radius_of_circle)
print(f"Area of circle: {area_of_circle}")
  1. ファイルのコンテンツ全体を選択します。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. make this more concise」と入力して Enter キーを押します。

    Copilot は、修正されたコードを提案します。 次に例を示します。

    import math
    
    def calculate_area_of_rectangle(length, width):
      return length * width
    
    def calculate_area_of_circle(radius):
      return math.pi * (radius ** 2)
    
    print(f"Area of rectangle: {calculate_area_of_rectangle(10, 5)}")
    print(f"Area of circle: {calculate_area_of_circle(7)}")
    
  4. Copilot の提案を評価し、変更に同意する場合は、次の手順を実行します:

    • VS Code および Visual Studio では: [承諾] をクリックします。
    • JetBrains: プレビュー アイコン (二重矢印) をクリックし、[すべての差分の適用] アイコン (二重山かっこ) をクリックします。

すべての Copilot の提案と同様に、修正されたコードがエラーなしで実行され、正しい結果が生成されることを常に確認する必要があります。

複雑なコード単位の分割

複数の操作を実行する大規模なメソッドまたは関数は、特定の操作の実行に重点を置いた小さく単純な関数よりも、再利用の機会が少なくなる可能性があります。 また、解釈とデバッグが難しくなる場合もあります。

Copilot を使用すると、複雑なコードのブロックを、再利用に適した小さな単位に分割するのに役立ちます。

次の Python コードは非常に単純な例ですが、単一の関数を特定の操作を実行する 2 つの関数に分割する原則を示しています。

import pandas as pd
from pandas.io.formats.style import Styler

def process_data(item, price):
    # Cleanse data
    item = item.strip()  # Strip whitespace from item
    price = price.strip()  # Strip whitespace from price
    price = float(price) # Convert price to a float
    # More cleansing operations 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.25"
process_data(item, price)

process_data 関数を分割するには:

  1. 関数名にカーソルを置きます。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. split into 2 separate functions: one for cleansing data, the other for printing」と入力して Enter キーを押します。

    Copilot は、修正されたコードを提案します。 次に例を示します。

    def cleanse_data(item, price):
      # Cleanse data
      item = item.strip()  # Strip whitespace from item
      price = price.strip()  # Strip whitespace from price
      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)
    

    メモ

    上記の提案例は、既存の関数を 3 つの関数に置き換えます。 3 番目の関数は、他の 2 つの関数を呼び出すだけで、process_data 関数を呼び出す既存のコードを使用できます。

  4. Copilot の提案を評価し、変更に同意する場合は、次の手順を実行します:

    • VS Code および Visual Studio では: [承諾] をクリックします。
    • JetBrains: プレビュー アイコン (二重矢印) をクリックし、[すべての差分の適用] アイコン (二重山かっこ) をクリックします。

すべての Copilot の提案と同様に、修正されたコードがエラーなしで実行され、正しい結果が生成されることを常に確認する必要があります。

読みやすくするために条件付きコードを書き換える

多くの場合、いくつかの方法で、さまざまな条件に応じて実行される、または実行されないコードを記述することができます。 一部の条件付き構造は、特定のユース ケースに適しており、代替の条件付き構造を選択すると、コードが読みやすくなることがあります。

この Java メソッドでは、一連の if ステートメントと else if ステートメントを使用して、実行する操作を決定します:

public String getSound(String animal) {
  if (animal == null) {
      System.out.println("Oops! A null animal?");
  } else if (animal.equalsIgnoreCase("Dog")) {
      return "Bark";
  } else if ( animal.equalsIgnoreCase("Cat")) {
      return "Meow";
  } else if ( animal.equalsIgnoreCase("Bird")) {
      return "Tweet";
  }
  return "Unknown";
}

switch ステートメントは、同じロジックを適用するより優れた方法である可能性があります。

  1. メソッド名にカーソルを置きます。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. 次のコマンドを入力します: rewrite the condition to use a switch and use Java 21 syntax with null case, but also add documentation and provide a better function name

    これは、単一のプロンプトを使用して、Copilot に複数の変更を加えるように求める方法を示しています。

  4. Enter キーを押します。

    Copilot は、修正されたコードを提案します。 次に例を示します。

    /**
     * Retrieves the sound made by a given 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 -> {
                System.out.println("Oops! A null animal?");
                yield "Unknown";
            }
            case String a when a.equalsIgnoreCase("Dog") -> "Bark";
            case String a when a.equalsIgnoreCase("Cat") -> "Meow";
            case String a when a.equalsIgnoreCase("Bird") -> "Tweet";
            default -> "Unknown";
        };
    }
    
  5. Copilot の提案を評価し、変更に同意する場合は、次の手順を実行します:

    • VS Code および Visual Studio では: [承諾] をクリックします。
    • JetBrains: プレビュー アイコン (二重矢印) をクリックし、[すべての差分の適用] アイコン (二重山かっこ) をクリックします。

すべての Copilot の提案と同様に、修正されたコードがエラーなしで実行され、正しい結果が生成されることを常に確認する必要があります。

別の構造を使用するようにコードを再フォーマットする

JavaScript に次の関数があるとします:

function listRepos(o, p) {
 return fetch(`https://api.github.com/orgs/${o}/repos?per_page=${parseInt(p)}`)
   .then((response) => response.json())
   .then( (data) => data);
}

コーディング標準で関数の矢印表記とパラメーターにわかりやすい名前を使用する必要がある場合は、Copilot を使用して、これらの変更を行うことができます。

  1. 関数名にカーソルを置きます。

  2. インライン チャットを開きます:

    • VS Code: Command+i (Mac) または Ctrl+i (Windows/Linux) を押します。
    • Visual Studio: Alt+/ キーを押します。
    • JetBrains IDE: Control+Shift+i (Mac) または Ctrl+Shift+g (Windows/Linux) を押します。
  3. use arrow notation and better parameter names」と入力して Enter キーを押します。

    Copilot は、修正されたコードを提案します。 次に例を示します。

    const listRepos = (org, perPage) => {
      return fetch(`https://api.github.com/orgs/${org}/repos?per_page=${parseInt(perPage)}`)
        .then(response => response.json())
        .then(data => data);
    };
    

シンボルの名前の改善

メモ

  • VS Code および Visual Studio のみ。
  • この機能のサポートは、使用している言語に合わせて IDE に適切な言語拡張機能をインストールするかどうかによって異なります。 すべての言語拡張機能でこの機能がサポートされているわけではありません。

適切に選択された名前は、コードの保守を簡単にするのに役立ちます。 VS Code と Visual Studio の Copilot は、変数や関数などのシンボルの別名を提案できます。

  1. シンボル名にカーソルを置きます。

  2. F2 キーを押します。

  3. Visual Studio のみ: Ctrl+Space キーを押します。

    Copilot は、別名を提案します。

    シンボル名の代わりに使用する VS Code のドロップダウン リストのスクリーンショット。

  4. ドロップダウン リストで、推奨される名前のいずれかを選択します。

    名前はプロジェクト全体で変更されます。

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy