has traditionally been a tedious but vital process. Refactoring is the work of taking some piece of code and cleansing it up, both by higher separation of issues, the Don’t Repeat Your self (DRY) precept, or different code hygiene rules.
Code refactors have at all times been vital, however with the discharge of coding brokers, we’re seeing greater coding outputs, which inevitably results in extra want for code refactoring. I an increasing number of typically discover myself in conditions the place some code must be refactored, although I don’t suppose this can be a warning signal, contemplating the quantity of code I output can also be considerably greater now with the assistance of LLMs.
Fortunately, the trouble to refactor code has considerably gone down for the reason that launch of LLMs.
On this article, I’ll undergo my high-level method to performing code refactoring utilizing coding brokers like Cursor or Claude Code. I’ll cowl my generic method and thought course of, so the mannequin you make the most of doesn’t matter.
Why carry out code refactoring
You need to carry out code refactoring everytime you discover lots of antipatterns in your code, or once you discover you (or your coding agent) is spending extra time than ought to be wanted on an implementation. Your threshold earlier than performing a refactoring also needs to be decrease than it was earlier than the discharge of LLMs, contemplating refactors are approach simpler and sooner to implement now utilizing coding brokers.
It is because a part of the coaching set for coding brokers is to refactor code, they usually’re particularly good at that. In lots of circumstances, I’d even say they’re higher than people, contemplating refactoring requires lots of working reminiscence:
- Remembering all variables
- Making certain enter/output after the refactor is identical as earlier than the refactor
- Which information to maneuver, delete, and add
Thus, it is best to carry out code refactoring when:
- You or your coding agent discovers lots of antipatterns in your code
- Implementations begin taking longer than they need to (an indication of unhealthy code)
And it is best to carry out code refactorings as a result of:
- They enhance iteration pace
- They’re comparatively low-cost to carry out with LLMs
My method to refactoring code
On this part, I’ll cowl my high-level method to refactoring code. I’ll undergo 4 steps:
- Discovering when to refactor
- What to think about earlier than the refactor
- What to think about through the refactor
- What to think about after the refactor
It will spotlight how one can method refactoring your self, in such generic phrases that you would be able to replicate the processing your self by yourself codebase.
1. Discovering when to refactor
Step one is at all times to find when it is best to determine to refactor your code. There typically isn’t a transparent line on when refactoring ought to be carried out or not, and it thus requires some intuition to know when is an effective time.
Nonetheless, it is best to apply some easy generic rules. If you happen to see lots of antipatterns within the code, for instance, with:
- A variety of duplicate code
- Lacking docstrings and performance sorts
- Poor separation of issues
You need to take into account refactoring.
Additionally, for those who discover your coding agent is spending longer than traditional studying by your codebase, attempting to grasp it. Or it struggles extra typically with implementing one thing, and errors elsewhere pop up. You also needs to take into account refactoring.
Nonetheless, selecting up this intuition takes time, and to start with, you possibly can try to refactor earlier fairly than later (contemplating that performing a refactor is reasonable with LLMs), after which alter once you study extra alongside the best way.
2. What to think about earlier than the refactor
Whenever you’ve come to this step, you could have determined {that a} sure a part of a code repository ought to be refactored. Now it’s good to plan for which scope the refactoring ought to cowl, since it is best to naturally scale back the refactoring scope as a lot as potential.
Scale back the scope of the refactoring as a lot as potential
I then begin planning, which I do in largely two methods:
- (non-compulsory) If I need to talk about generic architectural decision-making or high-level concepts, I begin chatting with Gemini within the console. I clarify my state of affairs, the trade-offs, the completely different options I’m contemplating, and all different related info. I then have a dialog with Gemini concerning the determination. Discover the phrase dialog. I’m not merely asking Gemini a query about remedy my drawback; I’m discussing with the mannequin what may very well be the perfect method, and attempting to grasp the problem as greatest as potential.
- I at all times begin off utilizing plan mode in both Cursor or Claude Code, the place you inform the mannequin what you need to do, it appears to be like by your code base, and it comes up with a plan for implement an answer into your code base. Typically, I copy over my dialog from Gemini (if I did that), and generally I merely begin my refactoring straight in Cursor.
Planning your method is tremendous helpful, because you develop into conscious of some points you weren’t conscious of earlier than, and might make choices with as a lot info as potential. Moreover, you possibly can learn by the plan that Cursor makes, and tweak it if want be. Most significantly, although, I like to recommend having a dialog along with your coding agent about method refactoring it, versus simply asking it a easy query and solely getting one response.
You need to try to have conversations along with your brokers, and never solely a single query and response
I like to recommend spending at the very least 10-Quarter-hour on this dialog when performing a major refactoring.
After a plan is made, I transfer on to step 3.
"""
Instance plan.md file after utilizing plan mode
On this state of affairs, the context is refactoring a messy, monolithic `server.js` (Categorical node app) right into a cleaner MVC (Mannequin-View-Controller) structure with TypeScript.
"""
***
# Plan: Refactor Monolithic Server to MVC Structure
## Context
At present, `src/server.js` incorporates all database connections, route definitions, and enterprise logic in a single file. We have to refactor this right into a modular construction utilizing TypeScript, splitting issues into Controllers, Companies, and Routes.
## Consumer Necessities
1. Convert the challenge to **TypeScript**.
2. Extract database logic right into a Singleton/Service.
3. Separate routes into `src/routes`.
4. Transfer enterprise logic to `src/controllers`.
## Proposed File Construction
* `src/app.ts` (Entry level)
* `src/config/database.ts` (DB connection)
* `src/routes/userRoutes.ts` (Route definitions)
* `src/controllers/userController.ts` (Request dealing with)
* `src/providers/userService.ts` (Enterprise logic)
---
## Step-by-Step Plan
### Part 1: Setup & Configuration
- [ ] Initialize TypeScript configuration (`tsconfig.json`).
- [ ] Set up mandatory `@sorts` dev dependencies (`node`, `categorical`).
- [ ] Rename `server.js` to `server.ts` briefly to resolve speedy linting errors.
### Part 2: Database Layer
- [ ] Create `src/config/database.ts`.
- [ ] Transfer the MongoDB connection string and connection logic from `server.ts` to `src/config/database.ts`.
- [ ] Make sure the database connection exports a strong singleton or connection perform.
### Part 3: Service & Controller Extraction
- [ ] Create `src/providers/userService.ts`.
- [ ] Transfer uncooked database queries (discover, create, replace) right here.
- [ ] Outline interfaces for Consumer information.
- [ ] Create `src/controllers/userController.ts`.
- [ ] Implement `getUsers`, `createUser`, and `updateUser` strategies.
- [ ] Import `userService` to deal with the logic.
- [ ] Guarantee correct sort typing for `Request` and `Response`.
### Part 4: Routing
- [ ] Create `src/routes/userRoutes.ts`.
- [ ] Setup `categorical.Router()`.
- [ ] Map endpoints (`/customers`, `/customers/:id`) to the particular Controller strategies.
### Part 5: Entry Level Cleanup
- [ ] Create `src/app.ts`.
- [ ] Initialize the Categorical app.
- [ ] Import and apply middleware (CORS, JSON physique parser).
- [ ] Mount `userRoutes`.
- [ ] Connect with the database utilizing `src/config/database.ts`.
- [ ] Delete the unique `src/server.js`.
### Part 6: Verification
- [ ] particular verification step: Begin the server utilizing `ts-node src/app.ts` to make sure no runtime errors.
- [ ] particular verification step: Check the `/customers` endpoint to make sure information circulate is undamaged.
---
### Would you want me to create this file construction for you now, or begin particularly with Part 1?
3. What to think about through the refactor
If you happen to’ve come to this step, you’ve already ready plan along with your coding agent, and also you’ve began performing the refactor. To make the refactor environment friendly and to make sure it really works in addition to potential, I preserve this stuff in thoughts:
- Be as lenient as you possibly can with permissions. In fact, watch out with harmful instructions, however having the agent be capable to carry out most instructions considerably hurries up the method
- Utilizing Claude. My expertise is that Claude Sonnet/Opus 4.5 are considerably the perfect and quickest coding mannequin on the market
- Inform the agent to create testing scripts if wanted. Typically the brokers simply attempt to debug from the code alone, however typically it’s higher to tell it to create a testing script the place it could see the enter and output
I then let the Coding agent run till it’s performed, which might take anyplace from a minute to twenty minutes. If it’s one of many first occasions you’re working code within the repo, you may need to permit record some instructions, however as talked about, I attempt to be lenient right here, particularly after we’re speaking about learn instructions, which might’t trigger any injury.
I additionally enable my agent to create check scripts and run them at will, to not solely debug the code from trying on the code, but additionally from seeing enter and output.
With this setup, I’m largely succeeding with the refactor with a most of some prompts forwards and backwards, and in lots of circumstances only one immediate.
4. What to think about after the refactor
After the refactoring is finished, it’s good to take into account the modifications. Typically it is best to look by all of the code completely, although generally it’s not mandatory. Nonetheless, I’ve some explicit suggestions after a refactor is finished:
- Ask the mannequin to match enter and output earlier than the refactor (level the mannequin to your principal or dev department, no matter department you department off of when beginning a brand new department). The mannequin will offer you an summary, and it is best to often be sure that the enter and output are the identical earlier than and after. This tip has saved me lots of bugs
- Run a coding assessment with a separate agent (begin it with a brand new context), which makes it simpler to level out errors your agent didn’t see when refactoring
- Ask Cursor to supply a considerate commit message, and create the PR for you. This each hurries up the method of getting the code to manufacturing, and it makes your PR’s extra descriptive
Significantly, my first level on evaluating in opposition to the principle/dev department is vital. Having the mannequin examine the enter and output with the earlier code and the present code has uncovered so many bugs that the mannequin didn’t see throughout refactoring.
I imagine that with even higher coding fashions, we’ll see fewer and fewer of those errors, although for now, I undoubtedly suppose it’s helpful to have the mannequin to a second assessment of the modifications, each by evaluating enter and output, and likewise by conducting a code assessment.
Conclusion
On this article, I’ve offered a high-level overview of how I carry out code refactors. I first mentioned know when a refactor is required, earlier than diving into the specifics of the refactoring method. I then coated how I exploit plan mode earlier than the refactoring, enable record instructions through the refactoring, and ask the mannequin to do a second assessment of the refactored code, with a refreshed context window.
I imagine LLM refactoring will develop into an increasing number of vital as we see greater and better coding output, due to LLM coding brokers. I additionally imagine that refactoring with LLMs is tremendous efficient, and one thing everybody ought to bear in mind, particularly when coding rather a lot utilizing coding brokers.
👉 My free eBook and Webinar:
🚀 10x Your Engineering with LLMs (Free 3-Day Email Course)
📚 Get my free Vision Language Models ebook
💻 My webinar on Vision Language Models
👉 Discover me on socials:
💌 Substack

