It’s time to enhance your coding process with AI-driven code improvement. The GPT family from OpenAI offers developers a wealth of opportunities to improve, review, fix, and even outsource code writing. Knowing how to use these large language models during the development process will soon become an essential tool in the developer toolkit.
Ever wondered how AI could transform your coding process? In this guide, we’ll demonstrate techniques for using ChatGPT or GPT-4 to review and refactor code, as well as discuss some limitations and provide handy resources for using these LLMs in your programming workflow.
We’ll start with ways we can review and refactor, and for each of these, you may want to experiment with different prompts and the provided techniques to unlock the full potential of AI-driven code improvement.
Note: I will use the term GPT4 during the content as this is the current model the examples are written in. ChatGPT (GPT3.5) works in a similar way and can be used interchangeably.
Refactoring Code with GPT-4 and ChatGPT
Refactoring code is crucial for several reasons: it enhances readability and maintainability, making it easier for developers to understand and modify the code. It also helps prevent potential bugs and ensures that your code adheres to established best practices. Ultimately, refactoring can lead to more efficient, reliable, and robust software.
GPT-4 can significantly contribute to this process. By using GPT-4 to review and assess your code, you can quickly identify areas for improvement and create cleaner, more efficient code. Leveraging GPT-4’s capabilities can save time and reduce human errors in the process, resulting in more consistent adherence to coding standards.
Modernizing Old Code
You can quickly modernize your code by providing your old function to GPT-4 and ask it to refactor it to modern coding practices.
Prompt: Refactor the following code to modern es6 programming standards
Before:
function tempConvert(temp, scale) {
var result = 0;
if (scale == "C") {
result = (temp - 32) * (5 / 9);
} else {
result = (temp * (9 / 5)) + 32;
}
return result.toFixed(1) + "°" + (scale == "C" ? "F" : "C");
}
After:
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;
const result = scale === "C"
? (temp - 32) * conversionFactor
: (temp * conversionFactor) + 32;
const resultUnit = scale === "C" ? "F" : "C";
return `${result.toFixed(1)}°${resultUnit}`;
}
In this refactored version, GPT4 quickly made the following improvements:
- Added JSDoc comments
- Converted the
tempConvert
function to an arrow function. - Replaced
var
withconst
for immutable variables. - Used strict equality checks (
===
) for string comparisons. - Introduced a constant to eliminate magic numbers.
- Simplified the return statement with template literals.
Adding Coding Best Practices or Principles
Your organisation or code base might use certain coding practices and styles that you want to keep. For situations like this, provide instructions to GPT4 on what particular coding practice, or style you’d like it to focus on.
Prompt: Review the following code and refactor it to make it more DRY and adopt the SOLID programming principles.
Note with the same input it has adopted the SOLID programming principle of Single Responsibility and split the function into 3. Unlike the ‘Modernize’ step earlier, it did not convert the function to an arrow function.
“By extracting the conversion logic into separate functions, we’ve improved the code’s adherence to the Single Responsibility Principle (part of SOLID), as each function now has a clear, focused purpose.”
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;
}
Detecting and Fixing Errors
Sometimes we are blind to the vulnerabilities or potential issues our code can create. Getting GPT-4 to review and address code issues can save you more than just time.
Prompt: Review this code for errors and refactor to fix any issues...
Input (Flawed) Function:
function updateTotalPrice(items, discountPercentage) {
let totalPrice = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
totalPrice += item.price * item.quantity;
}
const discount = totalPrice * (discountPercentage / 100);
totalPrice -= discount;
return totalPrice;
}
Output:
function updateTotalPrice(items, discountPercentage) {
if (!Array.isArray(items) || typeof discountPercentage !== 'number') {
throw new Error('Invalid input parameters');
}
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];
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;
}
Changes that GPT-4 made:
- Added input parameter validation to ensure items is an array and discountPercentage is a number.
- Checked boundary conditions for discountPercentage to ensure it’s within the 0-100 range.
- Added validation for item properties and their types to ensure price and quantity are numbers.
Create Boilerplate Code (*my favourite)
Starting new projects can be a painful. GPT-4 doesn’t know your business logic but it can be used to kick off the boring boilerplate code on day 1. This isn’t technically refactoring but it’s amazing and can be part of an process in the programming lifecycle.
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.
Transpiling Code
There are many reasons you may need to convert code from one language to another. You’ve found a repo with code for one language that you need in another, you’re moving code bases, or maybe your boss read an article on the latest front end framework and now you’re moving to {divisive new library}.
In any case, GPT-4 can provide assistance with a simple prompt.
Prompt: Rewrite the following code in Rust: ...
If your code is self-explanatory but requires commenting, this can be a huge time-saver.
Prompt: Add comments to the following code ...
Tips for Better Refactoring
Like many things in life, with GPT-4, you get out what you put in. In this case, providing more context, instructions, and guidance will usually produce better results.
Here’s a short list of tips and techniques to improve your code refactoring:
- Split your prompts: Try breaking your prompts and desired outcome across multiple steps. Keeping prompts to have a single outcome has shown to produce better results than combined prompts. For example, ask for a review, then ask for a refactor based on the review response. This may become less important in time as LLMs increase their token limit.
- Be Specific: Don’t be afraid to list exactly what you want, what you know, what is needed, and what not to include.
- Ask it to Reflect: A technique called reflexion has been shown to increase GPT4’s accuracy. Basically ask it ‘Why were you wrong?’ or get it to reflect and review its own response.
Limitations
This article is very pro-AI, however these models are not perfect and cannot (yet) accurately replicate business logic, among other things. Here’s a list of things to look out for and avoid when using GPT-4 to review or refactor your code:
- It can be (confidently) wrong: GPT4 is trained to sound convincing but that doesn’t mean its always right. Another great article on refactoring Golang with ChatGPT reported ‘It got rid of the type checks with the confident explanation that type-asserting a non-int value to an int type will return the zero value for the int type, but this is not correct and will panic‘.
- Saving time upfront may not be worth it in the long run: Sure, GPT4 can generate you 50 lines of code in a minute but it may end up taking you 45 minutes to debug and tweak it if it is not fit for your codebase. You would have been better off writing it yourself.
- It can be out of date: The technology world moves fast. “GPT-4 generally lacks knowledge of events that have occurred after the vast majority of its data cuts off (September 2021)“. You may encounter issues with any newly updated library, framework, or technology.
Conclusion
AI-powered programming is only new but it is here to stay. When used correctly it can save time and help us write better code. I hope you’ve enjoyed this article and have taken away some new skills to boost your programming productivity or error handling.