Skip to content

投稿

生成AIでコーディング生産性を向上させる5つの方法

2025年1月31日 • 11分で読める

生成AIでコーディング生産性を向上させる5つの方法

長年の経験を持つソフトウェア職人として、2023年のChatGPT導入以来、生成AIがソフトウェア開発に与える影響を目の当たりにしてきました。実践的な応用を通じて、この技術を活用して生産性を向上させる5つの強力な方法を特定しました。

1. 強化されたコード検索

生成AIを最も頻繁に活用するのは、技術情報の検索です。従来の検索エンジンでは正確な専門用語が必要でしたが、生成AIは概念とコンテキストを理解します。例えば、メソッドパラメータ最適化の原則を検索する際、次のように質問します:

プロンプト

What's the name of the programming concept where you should only pass parameters that are actually used by the method? Passing parameters to a method that aren't used by the method creates unneeded dependencies. 

生成AIは私が説明している概念(デメテルの法則)を理解し、正しい答えを提供するため、複数回の検索が不要になります。

2. 効率的なコード生成

生成AIは反復的なコーディングタスクの自動化に優れています。最近、大きなJSONファイルをデータベースのinsert文に変換する必要がありました。面倒な変換コードを書く代わりに、MS SQL Serverのinsert文を生成するための明確な指示とともにJSONデータをAIに提供しました。このアプローチにより、手動コーディング時間を数時間節約し、エラーの可能性を減らしました。

プロンプト:

Use the JSON data provided below and generate insert statements for MS SQL Server to be inserted into the dbo.Users table.

[  
{  
"Username": "musiclover87",  
"Lastname": "Smith",  
"Firstname": "Alice",  
"Birthdate": "1987-06-12",  
"Password": "password123",  
"FavoriteIceCream": "Chocolate Chip Cookie Dough",  
"FavoriteSuperhero": "Spider-Man"  
},  
{  
"Username": "bookworm92",  
"Lastname": "Johnson",  
"Firstname": "Bob",  
"Birthdate": "1992-03-21",  
"Password": "securePassword",  
"FavoriteIceCream": "Mint Chocolate Chip",  
"FavoriteSuperhero": "Batman"  
},  
{  
"Username": "gamergirl01",  
"Lastname": "Williams",  
"Firstname": "Carol",  
"Birthdate": "2001-11-05",  
"Password": "gamer4life",  
"FavoriteIceCream": "Strawberry",  
"FavoriteSuperhero": "Wonder Woman"  
},  
{  
"Username": "techieguy95",  
"Lastname": "Brown",  
"Firstname": "David",  
"Birthdate": "1995-08-18",  
"Password": "techmaster",  
"FavoriteIceCream": "Vanilla Bean",  
"FavoriteSuperhero": "Iron Man"  
},  
{  
"Username": "foodiequeen89",  
"Lastname": "Davis",  
"Firstname": "Emily",  
"Birthdate": "1989-04-29",  
"Password": "delicious123",  
"FavoriteIceCream": "Salted Caramel",  
"FavoriteSuperhero": "Captain Marvel"  
},  
{  
"Username": "traveler76",  
"Lastname": "Miller",  
"Firstname": "Frank",  
"Birthdate": "1976-12-02",  
"Password": "adventuretime",  
"FavoriteIceCream": "Coffee",  
"FavoriteSuperhero": "Thor"  
},  
{  
"Username": "fitnessfanatic98",  
"Lastname": "Wilson",  
"Firstname": "Grace",  
"Birthdate": "1998-09-15",  
"Password": "strongandfit",  
"FavoriteIceCream": "Mango Sorbet",  
"FavoriteSuperhero": "Black Widow"  
},  
{  
"Username": "photographylover85",  
"Lastname": "Moore",  
"Firstname": "Henry",  
"Birthdate": "1985-05-23",  
"Password": "pictureperfect",  
"FavoriteIceCream": "Pistachio",  
"FavoriteSuperhero": "Superman"  
},  
{  
"Username": "musicjunkie93",  
"Lastname": "Taylor",  
"Firstname": "Isabella",  
"Birthdate": "1993-02-08",  
"Password": "musicislife",  
"FavoriteIceCream": "Rocky Road",  
"FavoriteSuperhero": "Black Panther"  
},  
{  
"Username": "sportsfanatic88",  
"Lastname": "Anderson",  
"Firstname": "Jack",  
"Birthdate": "1988-10-30",  
"Password": "goteamgo",  
"FavoriteIceCream": "Cookies and Cream",  
"FavoriteSuperhero": "Captain America"  
}  
]

出力:


-- Inserting records into dbo.Users table

INSERT INTO dbo.Users (Username, Lastname, Firstname, Birthdate, Password, FavoriteIceCream, FavoriteSuperhero)
VALUES 
('musiclover87', 'Smith', 'Alice', '1987-06-12', 'password123', 'Chocolate Chip Cookie Dough', 'Spider-Man'),
('bookworm92', 'Johnson', 'Bob', '1992-03-21', 'securePassword', 'Mint Chocolate Chip', 'Batman'),
('gamergirl01', 'Williams', 'Carol', '2001-11-05', 'gamer4life', 'Strawberry', 'Wonder Woman'),
('techieguy95', 'Brown', 'David', '1995-08-18', 'techmaster', 'Vanilla Bean', 'Iron Man'),
('foodiequeen89', 'Davis', 'Emily', '1989-04-29', 'delicious123', 'Salted Caramel', 'Captain Marvel'),
('traveler76', 'Miller', 'Frank', '1976-12-02', 'adventuretime', 'Coffee', 'Thor'),
('fitnessfanatic98', 'Wilson', 'Grace', '1998-09-15', 'strongandfit', 'Mango Sorbet', 'Black Widow'),
('photographylover85', 'Moore', 'Henry', '1985-05-23', 'pictureperfect', 'Pistachio', 'Superman'),
('musicjunkie93', 'Taylor', 'Isabella', '1993-02-08', 'musicislife', 'Rocky Road', 'Black Panther'),
('sportsfanatic88', 'Anderson', 'Jack', '1988-10-30', 'goteamgo', 'Cookies and Cream', 'Captain America');

3. シームレスなコード変換

コード変換は、生成AIが非常に価値を発揮するもう一つの分野です。最近のC#アプリケーションをPythonに変換するプロジェクトでは、AIを2つの重要な方法で活用しました:

  1. PythonからC#への直接的な関数変換

  2. Entity FrameworkからSQLAlchemyへの複雑なORM変換

この機能により、移行プロセスが大幅に加速され、変換全体の一貫性が確保されました。

PythonからC#への変換:

プロンプト:

Convert the following Python code to C#.
def reverse_string(text): 
"""
Reverses a given string. 
	Args: text: The string to be reversed. 

Returns: The reversed string.

""" 
return text[::-1]

出力:

/// <summary>
/// Reverses a given string.
/// </summary>
/// <param name="text">The string to be reversed.</param>
/// <returns>The reversed string.</returns>
public static string ReverseString(string text)
{
	return new string(text.Reverse().ToArray());
}

4. 自動化されたコードドキュメント

ドキュメントは必須ですが、しばしば面倒な作業です。生成AIは、このプロセスを2つの方法で効率化します:

  1. コード要約:既存のコードを分析し、明確で簡潔な要約を提供

  2. ドキュメントヘッダー生成:コード品質基準を維持する包括的なメソッドドキュメントの作成

例えば、ソートアルゴリズムや複雑なビジネスロジックをドキュメント化する際、AIはチーム基準とベストプラクティスに従った明確で正確なドキュメントを生成できます。

プロンプト:

Generate a doc header for the below function adding the header and printing the complete function with the doc header.
def bubble_sort(list_):
  n = len(list_) 
  for i in range(n):
    # Flag to optimize, if no swaps occur, the list is sorted
    swapped = False
    # Last i elements are already in place
    for j in range(0, n-i-1):
      # Swap if the element found is greater than the next element
      if list_[j] > list_[j+1]:
        list_[j], list_[j+1] = list_[j+1], list_[j]
        swapped = True
    # If no two elements were swapped in inner loop, the list is sorted
    if not swapped:
      break
  return list_

出力:

def bubble_sort(list_):
    """
    Sorts a given list using the Bubble Sort algorithm.

    Args:
        list_: The list of elements to be sorted. Elements must be comparable.

    Returns:
        A new list containing all elements from the original list in ascending order.
        
    Example:
        >>> bubble_sort([64, 34, 25, 12, 22, 11, 90])
        [11, 12, 22, 25, 34, 64, 90]
    """
    n = len(list_) 
    for i in range(n):
        # Flag to optimize, if no swaps occur, the list is sorted
        swapped = False
        # Last i elements are already in place
        for j in range(0, n-i-1):
            # Swap if the element found is greater than the next element
            if list_[j] > list_[j+1]:
                list_[j], list_[j+1] = list_[j+1], list_[j]
                swapped = True
        # If no two elements were swapped in inner loop, the list is sorted
        if not swapped:
            break
    return list_

5. アプリケーションスキャフォールディング

生成AIの最も印象的な応用は、初期アプリケーション構造を生成する能力です。明確なスキーマや仕様が与えられれば、AIは以下を作成できます:

  • データベース作成スクリプト

  • ORMマッピング

  • 基本的なAPIエンドポイント

  • 初期UI実装

この機能により、ボイラープレートコードに費やす時間が大幅に削減され、さらなる開発のための一貫した基盤が確保されます。

プロンプト:

You are a Software Engineer working at a large corporation. Using the following database schema, generate the SQL scripts necessary to create these tables in Postgres. Then, generate the SQL Alchemy mapping files to use with FastAPI. Lastly, generate a simple web UI using FastAPI to list the orders.
User
- UserId
- FirstName
- LastName
- Address
- Address2
- City
- State
- ZipCode
- Username
- Password
- IsActive

Client
- ClientId
- Name
- Address
- Address2
- City
- State
- ZipCode
- IsActive

Order
- OrderId
- OrderDate
- InvoiceNumber
- DueDate
- ClientId
- UserId

OrderDetail
- OrderDetailId
- OrderId
- Description
- Rate
- Quantity
- LineTotal

Ledger
- TransactionId
- Debit
- Credit
- OrderId
- TransactionDate

出力:

...
出力は省略しますが、FastAPIを使用した完全なアプリケーションが生成されました。
...

初期設計を改善するために何ができるかを聞いてみましょう。

プロンプト 2:

That's a great start. What can we do to improve the application design?

出力:
より良いデバッグとエラーハンドリングのためにロギングを実装する。

logging.py (オプション)

import logging

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

def log_error(error):
    logger.error(f"An error occurred: {error}")

プロンプト 3:

Can you implement your suggestion to use Error Handling and generate the code for me?

出力:
特定の例外をグローバルに処理したい場合は、main.pyファイルでグローバル例外ハンドラーを定義することもできます。

main.py

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import app.routers.order_router as order_router
from .exceptions import OrderNotFoundException, InvalidInvoiceNumberException

app = FastAPI()

# Include the router
app.include_router(order_router.router)

@app.exception_handler(OrderNotFoundException)
async def order_not_found_exception_handler(request: Request, exc: OrderNotFoundException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail},
    )

@app.exception_handler(InvalidInvoiceNumberException)
async def invalid_invoice_number_exception_handler(request: Request, exc: InvalidInvoiceNumberException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail},
    )

ベストプラクティスと考慮事項

生成AIは強力ですが、以下のことが重要です:

  • 生成されたコードをレビューし検証する
  • 既存のコードベースとの一貫性を維持する
  • セキュリティへの影響を考慮する
  • 生成されたコードを徹底的にテストする
  • エンジニアリング判断の代替ではなく、アシスタントとしてAIを使用する

結論

生成AIは現代のソフトウェア開発において不可欠なツールとなりました。これらの5つのアプローチ(強化された検索、コード生成、変換、ドキュメント、アプリケーションスキャフォールディング)を活用することで、開発者はコード品質を維持しながら生産性を大幅に向上させることができます。

重要なのは、これらのツールの機能と限界を理解し、人間の専門知識を置き換えるのではなく強化するために戦略的に使用することです。これらの技術が進化するにつれて、開発ワークフローへの統合はますます価値あるものになるでしょう。

著者:Chuck Conwayはソフトウェアエンジニアリングと生成AIを専門としています。ソーシャルメディアで彼とつながりましょう:X (@chuckconway) または YouTube をご覧ください。

↑ トップに戻る

こちらもおすすめ