How to Review and Refactor Code with GPT-4 (and ChatGPT … – SitePoint

It’s time to enhance your coding process with AI-driven code improvement. The GPT family of models 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 prompted for the containted examples. ChatGPT (GPT3.5) works in a similar way and can be used interchangeably.
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.
You can quickly modernize your code by providing your old function to GPT-4 and ask it to refactor it to modern coding practices.
Note: This prompt example has introduced a logical error in the function. We’ve intentionally shown this example as a great as example of ‘you get what you ask for’. When asking ChatGPT to review the code for logical errors, it is able to identify them.
Prompt: Refactor the following code to modern es6 programming standards
Before:
After:
In this refactored version, GPT4 quickly made the following improvements:
Issues:
After (Take 2):
We the same prompt from … and voila, it returned a much better version of the function. This two, or more pass, approach is extremely effective.
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.”
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:
Output:
Changes that GPT-4 made:
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.
Not only are unit tests important for your code base but they can be a useful way to quickly validate anything produced by GPT-4.
Prompt: Create 2 unit tests for the provided code. One for a successful condition and one for failure.
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 ...
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:
Writing prompts for GPT-4 is much like writing functions. A well designed set of prompts is one where each has separated concerns and singular responsibilities. Here’s a simple chain of prompts to update, refactor, and review a piece of code. You may not need each step in your case.
You will notice that the produced function at the is very different to what we created earlier. In each step of the process we either improve the code or validate it’s efficacy before running the code on our system.
Note: The same input function from earlier was used but run on a different model and different day.
Get GPT-4 to re-write your code into the style you want. As seen above, this step will generally result in coherent output, in the style you want, but may introduce errors, so we do it first.
Prompt: Review the following code and re-write it to modern es6 programming standards and formatting: {{tempConvert function from earlier}}
GPT-4 Response:
Get a review of your code with recommendations to improve any logical or security concerns introduced. It’s important that we don’t ask for a refactor, just the reasoning behind wanting the refactor.
Prompt: Review your provided code 'tempConvert' for any logical or security concerns and provide a list of recommendations.
GPT-4 Response: Here are some recommendations for improving the tempConvert function to address logical concerns and make it more robust:
Validate the provided recommendations. As shown above reflexion is a powerful technique to improve the accuracy of the initial recommendations and try to eliminate any hallucinations.
This is not always required but it is worth asking if you are unsure about any recommendations. In our example, it just repeats the same recommendations. In this case, it did not provide any additional information but did confirm the recommendations were valid.
Prompt: Review your above recommendations. Tell me why you were wrong and if any recommendations were overlooked or incorrectly added?
GPT-4 Response: I apologize for any confusion. After reviewing the tempConvert function I provided earlier, I realized that I made an error in my previous response. I already incorporated strict equality (===) and template literals in the provided function.
However, my initial recommendations still apply to improve the function’s robustness and readability. To summarize, here are the updated recommendations:
I hope this clears up any confusion. The above recommendations should enhance the logical flow of the tempConvert function and make it more robust in handling various input scenarios.
Combine your reviews, recommendations and feedback and get GPT-4 to write your fancy new function.
Prompt: Re-write the convertTemp function based off your review and recommendations.
Finally, we ask it to create some simple JavaScript tests that we can run locally and validate the results of our fancy new function.
Prompt: Create two vanilla javascript tests for the above tempConvert function. One that is expected to pass and one that is expected to fail.
GPT-4 Response: Here are two simple vanilla JavaScript tests for the tempConvert function, one expected to pass and the other expected to fail:
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:
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.
Mark is the General Manager of SitePoint.com. He loves to read and write about technology, startups, programming languages, and no code tools.
© 2000 – 2023 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

source

Jesse
https://playwithchatgtp.com