生成式人工智能如何改變軟件開發 原創
采用人工智能編碼助手可以將軟件開發團隊的效率提高40%,其中包括代碼審查至調試的過程,同時可以有效應對現實世界的挑戰并遵循最佳實踐。
軟件開發專家Igboanugo David Ugochukwu表示,當他帶領的軟件開發團隊在去年開始使用人工智能編碼助手時,他對其能力持懷疑態度。基于其長達15年的編程經驗,他不相信大型語言模型能夠對實際的開發工作提供有意義的幫助。在六個月后,他的看法發生了根本性轉變,其開發團隊的工作效率提高了大約40%,同時代碼質量指標也有所提高。
但關鍵在于,這并不像“人工智能讓編碼變得更容易”那么簡單。實際應用中的情況遠比市場宣傳所描繪的更微妙、更有趣,并且從實用角度來看,也更具價值。
實際應用情況
Ugochukwu分享了近日發生的一件事。他正在調試Node.js后端一個嚴重的內存泄漏。這在以往意味著要花費數小時梳理代碼,添加控制臺日志,可能還需要花費更多的時間。然而,他將相關代碼和內存配置文件輸入到人工智能助手中,并要求它分析模式。
在幾分鐘之內,人工智能助手就發現了一些他未曾留意的一處細節——在一個閉包中意外地保持了WebSocket連接。這是一個微不足道卻難以察覺的錯誤。盡管人工智能并沒有神奇地修復它,但它比傳統的調試方法更快地指明了正確的方向。
真正有效的方法
根據其團隊在過去一年使用人工智能助手的經驗:
1.代碼評審
Python
1 def process_user_data(data):
2 if data['status'] == 'active':
3 user = User.objects.get(id=data['user_id'])
4 if user.subscription:
5 if user.subscription.status == 'valid':
6 return handle_active_user(user)
7 else:
8 return handle_inactive_subscription(user)
9 return handle_inactive_user()
人工智能助手發現了這一點,并提出了以下建議:
重構版本:
Python
1 def process_user_data(data):
2 if data['status'] != 'active':
3 return handle_inactive_user()
4
5 user = User.objects.get(id=data['user_id'])
6 if not user.subscription:
7 return handle_inactive_user()
8
9 return (handle_active_user(user)
10 if user.subscription.status == 'valid'
11 else handle_inactive_subscription(user))
雖然它并不是革命性突破,但始終比人類審閱者更快地發現這些可讀性問題。
2.測試生成
這是另一個意外的發現。以下是一個真實示例:
最初的功能:
Python
1 def calculate_order_total(items, discount_code=None):
2 subtotal = sum(item.price * item.quantity for item in items)
3 if discount_code:
4 discount = get_discount_amount(discount_code, subtotal)
5 return subtotal - discount
6 return subtotal
人工智能生成了這些測試用例:
Python
1 def test_calculate_order_total():
2 items = [
3 Item(price=10.0, quantity=2),
4 Item(price=15.0, quantity=1)
5 ]
6 assert calculate_order_total(items) == 35.0
7
8 def test_calculate_order_total_with_discount():
9 items = [Item(price=100.0, quantity=1)]
10 assert calculate_order_total(items, 'SAVE20') == 80.0
11
12 def test_calculate_order_total_empty():
13 assert calculate_order_total([]) == 0
14
15 def test_calculate_order_total_invalid_discount():
16 items = [Item(price=10.0, quantity=1)]
17 assert calculate_order_total(items, 'INVALID') == 10.0
它捕捉到了開發人員一開始可能會忽略的邊界案例。
不適用人工智能助手的情況
1.復雜的架構決策
Ugochukwu帶領的開發團隊最近需要重新設計身份驗證系統,以處理多租戶單點登錄(SSO)。人工智能助手提供的建議從技術上來說是正確的,但忽略了關于不同客戶端類型之間會話管理的關鍵現實因素。
2.場景復雜型調試
當一個bug涉及多個服務、復雜狀態或競爭條件時,人工智能工具仍然會遇到困難。它們可以幫助分析單個組件,但往往忽略了整體情況。
對開發工作流程的實際影響
以下是開發工作流程的實際變化:
在人工智能整合之前
Plain Text
1 1. Write code (2 hours)
2 2. Write tests (1 hour)
3 3. Debug issues (2 hours)
4 4. Code review (1 hour)
5
6 Total: ~6 hours per feature
在人工智能整合之后
Plain Text
1 1. Write code with AI assistance (1 hour)
2 2. AI generates test cases, developer adjusts (30 mins)
3 3. Debug with AI analysis (1 hour)
4 4. AI-assisted code review (30 mins)
5
6 Total: ~3 hours per feature
但問題是,這之所以能奏效,是因為開發團隊學會了如何有效地使用人工智能工具。雖然他們在第一個月的工作效率較低,但正在摸索正確的工作流程。
學到的最佳實踐
1.面向開發人員的提示工程
而不是:
Plain Text
1 "Write a function to process user data"
該開發團隊采取的做法是:
Plain Text
1 "Write a Python function that:
2
3 - Takes a user_id and data dictionary
4 - Validates required fields: name, email, age
5 - Handles missing fields with default values
6 - Raises ValidationError for invalid data
7 - Returns a processed user object
8
9 Use type hints and include error handling."
輸出內容質量上的差異十分顯著。
2.代碼審查策略
現在采取的做法是:
- 第一輪:利用人工智能進行風格、潛在漏洞和明顯問題的審查。
- 第二輪:人工審查業務邏輯和架構方面的問題。
- 最后一輪:再次利用人工智能檢查安全漏洞。
3.文檔生成
這改變了游戲規則。示例如下:
Python
1 # Original function with minimal docs
2
3 def process_payment(amount, user_id, method):
4
5 # ... implementation ...
人工智能將其擴展為:
Python
1 def process_payment(
2 amount: Decimal,
3 user_id: str,
4 method: PaymentMethod
5 ) -> PaymentResult:
6 """Process a payment transaction for a user.
7
8 Args:
9 amount: Transaction amount in user's local currency.
10 user_id: Unique identifier for the user.
11 method: Payment method object containing card/bank details.
12
13 Returns:
14 PaymentResult object containing transaction ID and status.
15
16 Raises:
17 InsufficientFundsError: If payment method has insufficient funds.
18 InvalidPaymentMethodError: If payment method is expired/invalid.
19 PaymentProcessingError: If payment gateway encounters an error.
20
21 Example:
22 >>> result = process_payment(
23 ... amount=Decimal('99.99'),
24 ... user_id='usr_123',
25 ... method=PaymentMethod(type='credit_card', token='tok_xyz')
26 ... )
27 >>> print(result.transaction_id)
28 'tx_abc123'
29 """
安全注意事項
在安全方面,必須極其謹慎。以下是吸取的一些教訓:
1.永遠不要讓人工智能生成安全關鍵代碼
不要做的示例:
Python
1 # DON'T: Let AI generate authentication logic
2 def verify_password(plain_text, hashed):
3 return hashlib.md5(plain_text.encode()).hexdigest() == hashed
2.始終檢查生成的SQL
已經看到人工智能建議易受攻擊的查詢:
SQL
1 -- DON'T: Raw string formatting
2 f"SELECT * FROM users WHERE id = '{user_id}'"
3
4 -- DO: Parameterized queries
5 "SELECT * FROM users WHERE id = %s", (user_id,)
展望未來
根據目前的趨勢和開發人員的經驗,以下是一些實際的變化趨勢:
1.集成開發環境(IDE)整合正變得日益重要
最新的人工智能驅動的集成開發環境(IDE)不僅提供代碼建議,還能理解整個代碼庫。例如,開發團隊的IDE異步函數在不同服務中的調用方式,標記了異步函數中潛在的競爭條件。
2.專業模型正在涌現
現在有一些人工智能模型專門針對某些框架或語言進行訓練。目前,獲得的針對TypeScript的特定建議明顯優于通用的代碼生成。
3.測試正在轉變
人工智能在生成人類可能錯過的邊緣案例和壓力測試方面做得越來越好,自從采用人工智能工具以來,測試覆蓋率有所提高。
結論
人工智能在短期內并不會取代開發人員。與其相反,人工智能可以提高軟件開發效率,幫助他們更早地發現漏洞,并處理編程中繁瑣且重復性的任務。關鍵在于理解其局限性,并將其作為高效的工具使用,而不是替代人類的判斷。
在這個數字時代中茁壯成長的開發人員并不是那些能編寫大量代碼的人,而是那些擅長與人工智能工具協作,同時對自己所構建的內容及其背后的邏輯與目的有著深刻認識的人。
Ugochukwu在撰寫本文的過程中,就巧妙地借助了人工智能的力量來輔助部分內容的創作。這正是關鍵所在。人工智能是一種工具,開發人員需要理解并且有效地利用它。
原文標題:??Beyond ChatGPT: How Generative AI Is Transforming Software Development??,作者:Igboanugo David Ugochukwu
