Close Menu
    Trending
    • Optimizing Data Transfer in Distributed AI/ML Training Workloads
    • Achieving 5x Agentic Coding Performance with Few-Shot Prompting
    • Why the Sophistication of Your Prompt Correlates Almost Perfectly with the Sophistication of the Response, as Research by Anthropic Found
    • From Transactions to Trends: Predict When a Customer Is About to Stop Buying
    • America’s coming war over AI regulation
    • “Dr. Google” had its issues. Can ChatGPT Health do better?
    • Evaluating Multi-Step LLM-Generated Content: Why Customer Journeys Require Structural Metrics
    • Why SaaS Product Management Is the Best Domain for Data-Driven Professionals in 2026
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » How to Perform Large Code Refactors in Cursor
    Artificial Intelligence

    How to Perform Large Code Refactors in Cursor

    ProfitlyAIBy ProfitlyAIJanuary 20, 2026No Comments12 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    has traditionally been a tedious but essential job. Refactoring is the work of taking some piece of code and cleansing it up, both by higher separation of considerations, the Don’t Repeat Your self (DRY) precept, or different code hygiene ideas.

    Code refactors have all the time 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 typically discover myself in conditions the place some code must be refactored, although I don’t assume it is a warning signal, contemplating the quantity of code I output can also be considerably greater now with the assistance of LLMs.

    Fortunately, the hassle to refactor code has considerably gone down because the launch of LLMs.

    On this article, I’ll undergo my high-level strategy to performing code refactoring utilizing coding brokers like Cursor or Claude Code. I’ll cowl my generic strategy and thought course of, so the mannequin you make the most of doesn’t matter.

    This infographic covers my high-level strategy to refactoring code utilizing LLMs. I first found when to refactor, normally triggered by detecting plenty of anti-patterns, and noticing that implementing code is now slower. I then begin planning the refactoring, utilizing Gemini, and the plan mode in Cursor. Shifting on, I execute the refactoring, the place I want the Claude fashions, and I’m liberal with my whitelisted instructions. I then confirm the refactor by asking my coding agent to check in opposition to the primary department and performing a secondary AI evaluation with a refreshed context. Picture by Gemini.

    Why carry out code refactoring

    You need to carry out code refactoring everytime you discover plenty of antipatterns in your code, or if 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 must also be decrease than it was earlier than the discharge of LLMs, contemplating refactors are method 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 plenty of circumstances, I’d even say they’re higher than people, contemplating refactoring requires plenty of working reminiscence:

    • Remembering all variables
    • Making certain enter/output after the refactor is similar as earlier than the refactor
    • Which recordsdata to maneuver, delete, and add

    Thus, you need to carry out code refactoring when:

    • You or your coding agent discovers plenty of antipatterns in your code
    • Implementations begin taking longer than they need to (an indication of dangerous code)

    And you need to carry out code refactorings as a result of:

    • They enhance iteration pace
    • They’re comparatively low-cost to carry out with LLMs

    My strategy to refactoring code

    On this part, I’ll cowl my high-level strategy to refactoring code. I’ll undergo 4 steps:

    1. Discovering when to refactor
    2. What to think about earlier than the refactor
    3. What to think about throughout the refactor
    4. What to think about after the refactor

    This can spotlight how one can strategy refactoring your self, in such generic phrases that you could replicate the processing your self by yourself codebase.

    1. Discovering when to refactor

    Step one is all the time to find when you need to resolve 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 efficient time.

    Nevertheless, you need to apply some easy generic ideas. In the event you see plenty of antipatterns within the code, for instance, with:

    • Numerous duplicate code
    • Lacking docstrings and performance varieties
    • Poor separation of considerations

    You need to take into account refactoring.

    Additionally, should you discover your coding agent is spending longer than typical studying via your codebase, attempting to grasp it. Or it struggles extra typically with implementing one thing, and errors elsewhere pop up. You must also take into account refactoring.

    Nevertheless, selecting up this intuition takes time, and to start with, you possibly can try and refactor earlier somewhat than later (contemplating that performing a refactor is reasonable with LLMs), after which alter if 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 may have determined {that a} sure a part of a code repository ought to be refactored. Now you might want to plan for which scope the refactoring ought to cowl, since you need to naturally cut back the refactoring scope as a lot as potential.

    Cut back the scope of the refactoring as a lot as potential

    I then begin planning, which I do in principally two methods:

    1. (non-compulsory) If I wish to focus on generic architectural decision-making or high-level concepts, I begin chatting with Gemini within the console. I clarify my scenario, the trade-offs, the totally different options I’m contemplating, and all different related info. I then have a dialog with Gemini concerning the resolution. Discover the phrase dialog. I’m not merely asking Gemini a query about easy methods to resolve my drawback; I’m discussing with the mannequin what might be the most effective strategy, and attempting to grasp the difficulty as finest as potential.
    2. I all the time begin off utilizing plan mode in both Cursor or Claude Code, the place you inform the mannequin what you wish to do, it appears via your code base, and it comes up with a plan for easy methods to implement an answer into your code base. Typically, I copy over my dialog from Gemini (if I did that), and typically I merely begin my refactoring instantly in Cursor.

    Planning your strategy is tremendous priceless, because you change into conscious of some points you weren’t conscious of earlier than, and may make choices with as a lot info as potential. Moreover, you possibly can learn via 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 easy methods to strategy refactoring it, versus simply asking it a easy query and solely getting one response.

    You need to attempt to have conversations along with your brokers, and never solely a single query and response

    I like to recommend spending a minimum of 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 situation, 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 considerations into Controllers, Companies, and Routes.
    
    ## Person 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
    
    ### Section 1: Setup & Configuration
    - [ ] Initialize TypeScript configuration (`tsconfig.json`).
    - [ ] Set up vital `@varieties` dev dependencies (`node`, `categorical`).
    - [ ] Rename `server.js` to `server.ts` briefly to resolve instant linting errors.
    
    ### Section 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 sturdy singleton or connection operate.
    
    ### Section 3: Service & Controller Extraction
    - [ ] Create `src/providers/userService.ts`.
        - [ ] Transfer uncooked database queries (discover, create, replace) right here.
        - [ ] Outline interfaces for Person 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`.
    
    ### Section 4: Routing
    - [ ] Create `src/routes/userRoutes.ts`.
        - [ ] Setup `categorical.Router()`.
        - [ ] Map endpoints (`/customers`, `/customers/:id`) to the particular Controller strategies.
    
    ### Section 5: Entry Level Cleanup
    - [ ] Create `src/app.ts`.
        - [ ] Initialize the Categorical 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`.
    
    ### Section 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 stream is undamaged.
    
    ---
    
    ### Would you want me to create this file construction for you now, or begin particularly with Section 1?

    3. What to think about throughout the refactor

    In the event you’ve come to this step, you’ve already ready a superb 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 maintain these items in thoughts:

    • Be as lenient as you possibly can with permissions. After all, watch out with harmful instructions, however having the agent have the ability to carry out most instructions considerably accelerates the method
    • Utilizing Claude. My expertise is that Claude Sonnet/Opus 4.5 are considerably the most effective 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 may possibly see the enter and output

    I then let the Coding agent run till it’s performed, which might take wherever from a minute to twenty minutes. If it’s one of many first occasions you’re working 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 might’t trigger any injury.

    I additionally enable my agent to create take a look at scripts and run them at will, to not solely debug the code from trying on the code, but in addition from seeing enter and output.

    With this setup, I’m principally succeeding with the refactor with a most of some prompts backwards and forwards, and in lots of circumstances only one immediate.

    4. What to think about after the refactor

    After the refactoring is finished, you might want to take into account the adjustments. Typically you need to look via all of the code totally, although typically it’s not vital. Nevertheless, I’ve some specific suggestions after a refactor is finished:

    • Ask the mannequin to check 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 give you an outline, and you need to normally be sure that the enter and output are the identical earlier than and after. This tip has saved me plenty 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 supply a considerate commit message, and create the PR for you. This each accelerates the method of getting the code to manufacturing, and it makes your PR’s extra descriptive

    Notably, my first level on evaluating in opposition to the primary/dev department is essential. Having the mannequin evaluate 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 assume it’s priceless to have the mannequin to a second evaluation of the adjustments, each via evaluating enter and output, and likewise by conducting a code evaluation.

    Conclusion

    On this article, I’ve offered a high-level overview of how I carry out code refactors. I first mentioned easy methods to know when a refactor is required, earlier than diving into the specifics of the refactoring strategy. I then lined 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 change into increasingly 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 take note, particularly when coding quite a bit 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

    🔗 LinkedIn

    🐦 X / Twitter



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleThe UK government is backing AI scientists that can run their own experiments
    Next Article The era of agentic chaos and how data will save us
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    Optimizing Data Transfer in Distributed AI/ML Training Workloads

    January 23, 2026
    Artificial Intelligence

    Achieving 5x Agentic Coding Performance with Few-Shot Prompting

    January 23, 2026
    Artificial Intelligence

    Why the Sophistication of Your Prompt Correlates Almost Perfectly with the Sophistication of the Response, as Research by Anthropic Found

    January 23, 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Data Poisoning in Machine Learning: Why and How People Manipulate Training Data

    January 17, 2026

    Inheritance: A Software Engineering Concept Data Scientists Must Know To Succeed

    May 22, 2025

    How to Create an AI-Powered Search Strategy with Wil Reynolds [MAICON 2025 Speaker Series]

    August 21, 2025

    A faster way to solve complex planning problems | MIT News

    April 16, 2025

    Sam Altman Admits: ChatGPT’s New Personality Is “Annoying”, Fix Coming This Week

    April 29, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    How to Evaluate Retrieval Quality in RAG Pipelines: Precision@k, Recall@k, and F1@k

    October 16, 2025

    Teaching AI models what they don’t know | MIT News

    June 3, 2025

    The AI Lab Is Scrambling to Make Peace in Washington

    October 29, 2025
    Our Picks

    Optimizing Data Transfer in Distributed AI/ML Training Workloads

    January 23, 2026

    Achieving 5x Agentic Coding Performance with Few-Shot Prompting

    January 23, 2026

    Why the Sophistication of Your Prompt Correlates Almost Perfectly with the Sophistication of the Response, as Research by Anthropic Found

    January 23, 2026
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.