程式碼移植
此技能用於將程式碼從一種語言移植到另一種語言。
輸入
- 目標語言
- 要移植的原始檔案或程式碼
流程
首先,建立目前程式碼中關鍵功能的概覽。請注意:
- 程式碼或單元測試所涵蓋的邊界情況
- 使用的程式庫及其在目標語言中的建議對應程式庫
使用結構化的使用者輸入或提問工具,逐一檢查每個程式庫,並與使用者確認應使用哪個對應程式庫。
提供的其他選項:
- 樁接程式庫功能(Stub library functionality)
- 從頭實作(Implement from scratch)
接下來,移植單元測試。以此作為驗證移植後程式碼的基礎。
最後,使用之前準備的概覽來移植程式碼。根據單元測試的結果反覆修正。
一般準則
- 使用目標語言常見的模式。
- 使用目標語言常見的命名慣例。
- 移植後的程式碼應能與原始程式碼對應,方便使用者找到相同的功能。
- 保留原始程式碼中的日誌與註解。
- 注意任何新的邊界情況。
- 記錄任何程式碼結構的變更,以幫助使用者定位。
成功標準
- 單元測試通過(若有的話)。
- 程式碼風格檢查通過(若有的話)。
- 所有關鍵功能都已實作。
- 所有識別出的邊界情況都已處理。
- 所有需要的程式庫都已安裝並可供使用。
範例
原始程式碼範例
/**
* 計算包含任何折扣及稅金後的最終產品價格。
*
* 遇到無效折扣時會擲出錯誤。
*/
export function calculatePrice(basePrice: number, discount: number | null, taxRate: number): number {
let discountAmount = 0;
if (discount) {
if (discount >= 1) {
// 如果折扣設定錯誤,可能會算出負數價格。
// 在向使用者顯示無效價格之前中止。
throw new Error('Invalid discount');
}
discountAmount = basePrice * discount;
}
const taxAmount = (basePrice - discountAmount) * taxRate;
return (basePrice - discountAmount) + taxAmount;
}
概覽範例
關鍵功能:
calculatePrice函式接受基本價格、折扣百分比與稅率,並計算產品的最終價格。- 邊界情況:
- 折扣可以為 null
- 若折扣大於或等於 1,則擲出例外以防止無效價格。
- 邊界情況:
移植後的程式碼範例
def calculate_price(base_price: float, discount: Optional[float], tax_rate: float) -> float:
"""
計算包含任何折扣及稅金後的最終產品價格。
遇到無效折扣時會擲出例外。
"""
discount_amount = 0
if discount is not None:
if discount >= 1:
# 如果折扣設定錯誤,可能會算出負數價格。
# 在向使用者顯示無效價格之前中止。
raise Exception('Invalid discount')
discount_amount = base_price * discount
tax_amount = (base_price - discount_amount) * tax_rate
return (base_price - discount_amount) + tax_amount
回應範例
我已將程式碼移植到 Python。
calculatePrice現在是calculate_price