How I use ChatGPT for refactoring code in my project

Pushkar Shirodkar
2 min readMar 3, 2024

Image by Uncle Memes

While ChatGPT3.5 (current version) is not smart enough to refactor large chunks of code, it can still be a useful tool in refactoring small chunks of code.

Usage could be various, however I’m mentioning a few of them which I’ve personally used

  • Optimising function block
  • Writing test cases using jest
  • Changing code to generate different outputs based on previous output results.
image taken from image flip

Prompt : Can you help me with code optimisation, you need to use switch case whenever possible

At this step. I copy my code from vscode and past it in the chat window.

Prompt 2: optimise the below code

export const getEnvVariableOrThrow: GetEnvVariableFn = (key) => {
const value = getEnvVariable(key);
if (!value) {
throw new Error(`Environment variable ${key} is not defined`);
}
return value;
}

Here the optimised code it generated.

export const getEnvVariableOrThrow: GetEnvVariableFn = (key) => {
const value = getEnvVariable(key) ?? (() => { throw new Error(`Environment variable ${key} is not defined`); })();
return value;
}

It also responded to what changes have been made and what optimization was performed.

In this version, if getEnvVariable(key) returns null or undefined, it will throw an error using the nullish coalescing operator. This makes the code a bit more concise, but it might not be as readable for everyone. So, it's essential to consider readability and maintainability when optimizing code. In this case, your original version might be preferable due to its clarity.

GIF by Giphy

Pretty amazing! In the next steps, I plan to create a Python bot that’ll automatically refactor my code and generate a pull request. I’ll update you with an article for the same.

GIF BY Giphy

If you like my content, consider following to get more funny and interesting articles 🥰.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Pushkar Shirodkar
Pushkar Shirodkar

Written by Pushkar Shirodkar

Full-stack web developer by day, tech explorer by night. Passionate about tech and electronics! 🚀 💻✨ #TechEnthusiast #VLSI #WebDev

No responses yet

Write a response