最近各种AI频繁出现,是时候通过 AI 驱动的代码改进来增强您的编码过程了。OpenAI 的 GPT 系列模型为开发人员提供了大量改进、审查、修复代码的机会。我们需要了解如何在开发过程中使用这些大型语言模型让其更好的辅助我们编码。
重构代码是非常重要的,因为它能够提高代码的可读性和可维护性,让开发人员更容易理解和修改代码。重构还有助于避免潜在的错误,确保代码符合最佳实践。重构可以带来更高效、更可靠和更健壮的软件。而现在,GPT可以在这一过程中发挥重要的作用。通过利用 GPT 审核和评估代码,可以快速确定需要改进和优化的部分,并创建更简洁、更高效的代码。使用 GPT 的功能能够节省时间并减少人为错误,从而更一致地遵守编码标准。
优化老版本代码
注意在优化老逻辑的时候一定要注意其原逻辑有没有所谓的补丁,因为有逻辑补丁在其中可能会导致优化后逻辑错乱。优化版本的prompt最好使用英文提示词,我们来个例子:
prompt:Refactor the following code to modern es6 programming standards
以前的:
function tempConvert(temp, scale) { // Vague function name
var result = 0; // 'var' is so es2015
if (scale == "C") { // Is this the correct way to compare strings?
result = (temp - 32) * (5 / 9); // Magic numbers
} else {
result = (temp * (9 / 5)) + 32;
}
return result.toFixed(1) + "°" + (scale == "C" ? "F" : "C"); // This line feels a bit cluttered...
}
升级后的:
/**
* Converts a temperature between Celsius and Fahrenheit.
* @param {number} temp - The temperature value to convert.
* @param {string} scale - The temperature scale ('C' or 'F') to convert from.
* @return {string} The converted temperature value, formatted with one decimal place and the appropriate unit.
*/
const tempConvert = (temp, scale) => {
const isValidScale = scale === "C" || scale === "F";
if (!isValidScale) {
throw new Error("Invalid scale: must be 'C' or 'F'.");
}
const conversionFactor = 5 / 9; // <-- Note: This is not correct when
const result = scale === "C"
? (temp - 32) * conversionFactor
: (temp * conversionFactor) + 32;
const resultUnit = scale === "C" ? "F" : "C";
return `${result.toFixed(1)}°${resultUnit}`;
}
在这个重构版本中,GPT 快速进行了以下改进:
- 添加了 JSDoc 注释
- 已将函数转换为箭头函数。
tempConvert
- 替换为不可变变量。
var const
- 对字符串比较使用了严格的相等性检查。
- 引入了一个常量来消除幻数。
- 使用模板文本简化了返回语句。
其实还可以进行优化,最终比较好的展现为:
function convertTemperature(temperature, scale) {
const isValidScale = scale === "C" || scale === "F";
if (!isValidScale) {
throw new Error("Invalid scale: must be 'C' or 'F'.");
}
const convertedTemperature = scale === "C"
? (temperature * (9 / 5)) + 32
: (temperature - 32) * (5 / 9);
const resultUnit = scale === "C" ? "F" : "C";
return `${convertedTemperature.toFixed(1)}°${resultUnit}`;
}
优化编码方式
有时候可能需要保留的某些编码方式。对于此类情况,请向 GPT 提供说明,说明希望它关注哪些特定的编码格式。
prompt:Review the following code and refactor it to make it more DRY and adopt the SOLID programming principles.
通过将转换逻辑提取到单独的函数中,我们提高了代码对单一责任原则(SOLID 的一部分)的遵守程度,因为每个函数现在都有一个明确、集中的目的。具体代码:
function tempConvert(temp, scale) {
const isValidScale = scale === "C" || scale === "F";
if (!isValidScale) {
throw new Error("Invalid scale: must be 'C' or 'F'.");
}
const result = scale === "C" ? celsiusToFahrenheit(temp) : fahrenheitToCelsius(temp);
const resultUnit = scale === "C" ? "F" : "C";
return `${result.toFixed(1)}°${resultUnit}`;
}
function celsiusToFahrenheit(temp) {
const conversionFactor = 9 / 5;
return (temp * conversionFactor) + 32;
}
function fahrenheitToCelsius(temp) {
const conversionFactor = 5 / 9;
return (temp - 32) * conversionFactor;
}
检测和修复错误
有时我们对代码可能产生的漏洞或潜在问题很难发现。让 GPT 审查和解决代码问题岂不是美滋滋。
prompt:Review this code for errors and refactor to fix any issues
//有bug的代码
function updateTotalPrice(items, discountPercentage) {
let totalPrice = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
totalPrice += item.price * item.quantity;
}
// Potential error: discountPercentage is not validated or checked for boundary conditions
const discount = totalPrice * (discountPercentage / 100);
totalPrice -= discount;
return totalPrice;
}
//修复后的
function updateTotalPrice(items, discountPercentage) {
// Fix 1: Validate input parameters
if (!Array.isArray(items) || typeof discountPercentage !== 'number') {
throw new Error('Invalid input parameters');
}
// Fix 2: Check for boundary conditions of discountPercentage
if (discountPercentage < 0 || discountPercentage > 100) {
throw new Error('Invalid discount percentage value. It should be between 0 and 100');
}
let totalPrice = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Fix 3: Validate item properties and types
if (!item.hasOwnProperty('price') || !item.hasOwnProperty('quantity') ||
typeof item.price !== 'number' || typeof item.quantity !== 'number') {
throw new Error('Invalid item properties');
}
totalPrice += item.price * item.quantity;
}
const discount = totalPrice * (discountPercentage / 100);
totalPrice -= discount;
return totalPrice;
}
- 添加了输入参数验证,以确保项目是数组,折扣百分比是数字。
- 检查了折扣百分比的边界条件,以确保它在 0-100 范围内。
- 添加了对属性及其类型的验证,以确保价格和数量为数字。
创建样板代码
开始新项目可能不会用到GPT。因为GPT不知道您的业务逻辑,但它可用之后的样板代码生成。
prompt:Write me a boilerplate Node.js function that will take a variable of type User, validate that the user has the right permissions, fetch an array of item type Posts from a postgres database and return them. Leave comments for business logic
创建单元测试
要想保证代码的健壮性我们需要单元测试,具体就不过多介绍单元测试了。
prompt:Create 2 unit tests for the provided code. One for a successful condition and one for failure.
转译代码
如果需要将代码从一种语言转换为另一种语言,那么可以用GPT试试,你会惊叹一句『真香』。
prompt:Rewrite the following code in Rust
向代码添加注释
对于老的屎山一样的代码逻辑,肉眼难以看懂,我们也可以用GPT。
prompt:Add comments to the following code
优化prompt
在输入prompt过程中我们要给出更明确的重构提示,在这种情况下,提供更多上下文、说明和指导通常会产生更好的结果。
- **拆分提示:**尝试在多个步骤中打破提示和预期结果。事实证明,保持提示具有单个结果比组合提示产生更好的结果。例如,请求评审,然后根据评审响应请求重构。
- **举个例子:**提供预期的输入、数据和输出,以提高准确性质量。
- 要具体:要准确地列出你想要什么,你知道什么,需要什么,不包括什么。
- 要求它反映:你可以问它“你为什么错了?”或者让它反思和审查自己的回答。
根据上面描述的优化提示词,我们在验证一下上面的重构能力。
例如:
- 优化老版本代码的prompt:
Review the following code and re-write it to modern es6 programming standards and formatting: {{tempConvert function from earlier}}
const tempConvert = (temp, scale) => { // More descriptive function name
let result = 0; // Use 'let' instead of 'var'
const fahrenheitToCelsius = (temp - 32) * (5 / 9);
const celsiusToFahrenheit = (temp * (9 / 5)) + 32;
if (scale === "C") { // Use strict equality operator (===) for comparison
result = fahrenheitToCelsius;
} else {
result = celsiusToFahrenheit;
}
const convertedScale = scale === "C" ? "F" : "C";
return `${result.toFixed(1)}°${convertedScale}`; // Use template literals for cleaner string concatenation
};
- 编写代码的prompt:
Re-write the convertTemp function based off your review and recommendations.
const fahrenheitToCelsius = temp => (temp - 32) * (5 / 9);
const celsiusToFahrenheit = temp => (temp * (9 / 5)) + 32;
const tempConvert = (temp, scale) => {
if (typeof temp !== 'number' || (scale !== 'C' && scale !== 'F')) {
throw new Error('Invalid input. Temp must be a number and scale must be either "C" or "F".');
}
let result = 0;
if (scale === 'C') {
result = fahrenheitToCelsius(temp);
} else if (scale === 'F') {
result = celsiusToFahrenheit(temp);
} else {
throw new Error('Invalid scale value. Scale must be either "C" or "F".');
}
const convertedScale = scale === "C" ? "F" : "C";
return `${result.toFixed(1)}°${convertedScale}`;
};
- 创建测试的prompt:
Create two vanilla javascript tests for the above tempConvert function. One that is expected to pass and one that is expected to fail
const testTempConvertPass = () => {
const inputTemp = 32;
const inputScale = 'C';
const expectedResult = '0.0°C';
const result = tempConvert(inputTemp, inputScale);
if (result === expectedResult) {
console.log('Test pass: tempConvert with valid input');
} else {
console.error(`Test fail: tempConvert with valid input. Expected ${expectedResult} but got ${result}`);
}
};
const testTempConvertFail = () => {
try {
const inputTemp = 32;
const inputScale = 'InvalidScale';
tempConvert(inputTemp, inputScale);
console.error('Test fail: tempConvert with invalid input should throw an error');
} catch (error) {
console.log('Test pass: tempConvert with invalid input');
}
};
// Run the tests
testTempConvertPass();
testTempConvertFail();
需要注意的是这些模型并不完美,有可能不能准确地复制业务逻辑等。所以在实际使用过程中也需要我们开发人员去检查逻辑。确定生成的内容与原内容逻辑一致。如果使用得当,它可以节省时间并帮助我们编写更好的代码