Skip to content

文章

5 种方式通过生成式 AI 提升编码生产力

2025年1月31日 • 10 分钟阅读

5 种方式通过生成式 AI 提升编码生产力

作为一名拥有多年从业经验的软件工匠,自 2023 年 ChatGPT 推出以来,我见证了生成式 AI 对软件开发的影响。通过实际应用,我已经确定了五种强大的方式来利用这项技术提升生产力。

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 文件转换为数据库插入语句。与其编写繁琐的转换代码,我向 AI 提供了 JSON 数据和生成 MS SQL Server 插入语句的明确说明。这种方法节省了数小时的手动编码时间,并降低了出错的可能性。

提示:

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:

  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 以两种方式简化了这个过程:

  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

输出:

...
I'm saving you from the output, but it generated an entire application using 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 已成为现代软件开发中不可或缺的工具。通过利用这五种方法——增强搜索、代码生成、翻译、文档和应用程序脚手架——开发人员可以显著提高生产力,同时保持代码质量。

关键是理解这些工具的能力和局限性,并战略性地使用它们来增强而非替代人类专业知识。随着这些技术的发展,它们在开发工作流程中的集成将变得越来越有价值。

作者:Chuck Conway 是一位 AI 工程师,拥有近 30 年的软件工程经验。他构建实用的 AI 系统——内容管道、基础设施代理和解决实际问题的工具——并分享他沿途的学习成果。在社交媒体上与他联系:X (@chuckconway) 或访问他的 YouTubeSubStack

↑ 返回顶部

你可能也喜欢