AI Refactoring for larger files


I had some really ugly code in description.js that had grown tremendously in size over 2years. As context: description.js is the centerpiece for displaying any sort of visual description, including resizing, badges, icons, etc. It handles 95% of the interaction with the .json data files.

Description.js

As of last week, description.js had reached the atrocious size of around 2800 lines of code - which is extremely bad, to put it mildly. It’s also the biggest single file in the project aside from the third-party libraries. I largely got there due to manually adding individual pieces over time - with a focus on maintainability, not performance.

Needless to say, none of the finer tricks of JavaScript were employed by me here. In a project like this, which is subject to permanent change, it’s better to have maintainability as a non-functional focus rather than performance. Yet, 2800 lines of code were too much, and I was forced to either slim it down or break it up into multiple smaller files (which I totally did not want to do, in all fairness).

I currently have access to the paid version of OpenAI GPT-4o - which allows uploading of files and also has a large token window of, if I recall correctly, 128k. I pasted the file to ChatGPT, and it refactored the entire thing in about ~2 minutes. The prompt output is very annoying, and you need to confirm multiple times in between that you want to continue generating if the output exceeds a certain length.

Yet, I was pleasantly surprised that it produced almost flawlessly working code on the first try; something I did not expect. However, it messed up on some really subtle details regarding the positioning of elements. But as said, in all other regards, it was 99% perfect - strong. Long story short, I manually copied and pasted chunks of the file and backtested for roughly half an hour to ensure everything refactored worked fine and did not break anything.

Refactor Result

At the end of it, I had an identically working and refactored clean file that was shrunk down to around 1800 lines of code. AI refactoring saved me a whopping 1000 lines of code. I mean - just look at this example as it created the part on the right - it took my dumb code and replaced it with a for- and a foreach-loop that are much more space efficient:

Refactor Result

I could’ve done that manually as well but it eventually saves me a tremendous amount of work. I can highly recommend AI refactoring. However, you cannot omit the tests. You need to test the stuff AI generates. It still has tiny and subtle bugs (especially once you deal with exotic edge cases) and they’re difficult to track down.

comments powered by Disqus