最近各种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 快速进行了以下改善:

  1. 增加了 JSDoc 注释
  2. 已将函数转换为箭头函数。tempConvert
  3. 替换为不行变变量。var const
  4. 对字符串比较运用了严厉的相等性查看。
  5. 引入了一个常量来消除幻数。
  6. 运用模板文本简化了回来语句。

其实还能够进行优化,最终比较好的展现为:

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;
}
  1. 增加了输入参数验证,以保证项目是数组,扣头百分比是数字。
  2. 查看了扣头百分比的边界条件,以保证它在 0-100 范围内。
  3. 增加了对特点及其类型的验证,以保证价格和数量为数字。

创立样板代码

开始新项目或许不会用到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.0C';
  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();

需求注意的是这些模型并不完美,有或许不能准确地仿制事务逻辑等。所以在实际运用进程中也需求咱们开发人员去查看逻辑。确认生成的内容与原内容逻辑一致。假如运用妥当,它能够节省时间并协助咱们编写更好的代码