has traditionally been a tedious but essential 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 ideas.
Code refactors have at all times been essential, however with the discharge of coding brokers, we’re seeing greater coding outputs, which inevitably results in extra want for code refactoring. I increasingly more usually discover myself in conditions the place some code must be refactored, although I don’t suppose it is a warning signal, contemplating the quantity of code I output can be considerably greater now with the assistance of LLMs.
Fortunately, the trouble to refactor code has considerably gone down because the 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
It’s best to carry out code refactoring everytime you discover a whole lot of antipatterns in your code, or once you discover you (or your coding agent) is spending extra time than needs 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 means simpler and sooner to implement now utilizing coding brokers.
It’s because a part of the coaching set for coding brokers is to refactor code, they usually’re particularly good at that. In a whole lot of circumstances, I’d even say they’re higher than people, contemplating refactoring requires a whole lot of working reminiscence:
- Remembering all variables
- Guaranteeing enter/output after the refactor is similar as earlier than the refactor
- Which information to maneuver, delete, and add
Thus, you must carry out code refactoring when:
- You or your coding agent discovers a whole lot of antipatterns in your code
- Implementations begin taking longer than they need to (an indication of dangerous code)
And you must carry out code refactorings as a result of:
- They improve 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 throughout the refactor
- What to think about after the refactor
It will spotlight how one can method refactoring your self, in such generic phrases you could replicate the processing your self by yourself codebase.
1. Discovering when to refactor
Step one is at all times to find when you must determine to refactor your code. There usually isn’t a transparent line on when refactoring needs to be carried out or not, and it thus requires some intuition to know when is an efficient time.
Nevertheless, you must apply some easy generic ideas. In the event you see a whole lot of antipatterns within the code, for instance, with:
- A number of duplicate code
- Lacking docstrings and performance sorts
- Poor separation of issues
It’s best to take into account refactoring.
Additionally, if you happen to discover your coding agent is spending longer than traditional studying by way of your codebase, making an attempt to grasp it. Or it struggles extra usually with implementing one thing, and errors elsewhere pop up. You also needs to take into account refactoring.
Nevertheless, selecting up this intuition takes time, and at first, you may try and refactor earlier fairly than later (contemplating that performing a refactor is reasonable with LLMs), after which regulate once you be taught extra alongside the best way.
2. What to think about earlier than the refactor
Once you’ve come to this step, you might have determined {that a} sure a part of a code repository needs to be refactored. Now it’s worthwhile to plan for which scope the refactoring ought to cowl, since you must naturally scale back the refactoring scope as a lot as doable.
Cut back the scope of the refactoring as a lot as doable
I then begin planning, which I do in largely two methods:
- (optionally available) 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 data. I then have a dialog with Gemini concerning the determination. Discover the phrase dialog. I’m not merely asking Gemini a query about tips on how to remedy my downside; I’m discussing with the mannequin what might be the perfect method, and making an attempt to grasp the difficulty as finest as doable.
- 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 by way of your code base, and it comes up with a plan for tips on how to implement an answer into your code base. Generally, I copy over my dialog from Gemini (if I did that), and typically 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 may make choices with as a lot data as doable. Moreover, you may learn by way of the plan that Cursor makes, and tweak it if want be. Most significantly, although, I like to recommend having a dialog together with your coding agent about tips on how to method refactoring it, versus simply asking it a easy query and solely getting one response.
It’s best to try to have conversations together 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 big 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` (Specific 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` accommodates 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 mission 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/companies/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` quickly to resolve fast 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/companies/userService.ts`.
- [ ] Transfer uncooked database queries (discover, create, replace) right here.
- [ ] Outline interfaces for Consumer knowledge.
- [ ] 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 Specific app.
- [ ] Import and apply middleware (CORS, JSON physique parser).
- [ ] Mount `userRoutes`.
- [ ] Hook up 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 knowledge circulation is unbroken.
---
### Would you want me to create this file construction for you now, or begin particularly with Part 1?
3. What to think about throughout the refactor
In the event you’ve come to this step, you’ve already ready a very good plan together 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 doable, I hold this stuff in thoughts:
- Be as lenient as you may with permissions. After all, watch out with harmful instructions, however having the agent have the ability to carry out most instructions considerably hastens 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. Generally the brokers simply attempt to debug from the code alone, however usually it’s higher to tell it to create a testing script the place it will probably see the enter and output
I then let the Coding agent run till it’s accomplished, which may take wherever from a minute to twenty minutes. If it’s one of many first instances you’re operating code within the repo, you might need to permit record some instructions, however as talked about, I attempt to be lenient right here, particularly once we’re speaking about learn instructions, which may’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 worthwhile to take into account the adjustments. Generally you must look by way of all of the code completely, although typically it’s not mandatory. Nevertheless, 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 most important or dev department, no matter department you department off of when beginning a brand new department). The mannequin will offer you an outline, and you must often be certain that the enter and output are the identical earlier than and after. This tip has saved me a whole lot of bugs
- Run a coding evaluation 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 offer a considerate commit message, and create the PR for you. This each hastens 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 primary/dev department is essential. 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 positively suppose it’s helpful to have the mannequin to a second evaluation of the adjustments, each by way of evaluating enter and output, and in addition by conducting a code evaluation.
Conclusion
On this article, I’ve supplied a high-level overview of how I carry out code refactors. I first mentioned tips on how to 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 throughout the refactoring, and ask the mannequin to do a second evaluation of the refactored code, with a refreshed context window.
I imagine LLM refactoring will develop into increasingly more essential 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 have in mind, particularly when coding so much utilizing coding brokers.
👉 My free eBook and Webinar:
🚀 10x Your Engineering with LLMs (Free 3-Day E-mail Course)
📚 Get my free Imaginative and prescient Language Fashions e book
💻 My webinar on Imaginative and prescient Language Fashions
👉 Discover me on socials:
💌 Substack















