Loading...

How to Use an LLM to Refactor and Improve Your Code

Getting your code to work is often just the first step. Writing code that is clean, efficient, and easy for others (and your future self) to understand is a separate, crucial skill. This process of improving existing code without changing its functionality is called refactoring, and it's where a large language model (LLM) can be an invaluable partner.

Image Description

This guide provides a practical workflow for using an LLM as an expert code reviewer. You'll learn how to craft prompts that help you simplify complex functions, improve performance, and add professional-grade documentation to your projects.

What is Code Refactoring (and Why Use an LLM)?

Code refactoring is the process of restructuring computer code—changing the factoring—without changing its external behavior. The goal is to improve nonfunctional attributes of the software, such as readability, complexity, maintainability, and performance.

An LLM is perfectly suited for this task because it has been trained on billions of lines of high-quality, open-source code. It has learned the patterns, conventions, and idioms that define clean code in many different languages. It can act as a patient senior developer, instantly spotting areas for improvement that you might overlook.

Common refactoring tasks for an LLM include:

  • Simplifying complex logic or nested loops.
  • Making code more idiomatic (e.g., more "Pythonic").
  • Adding comments and documentation (docstrings).
  • Identifying potential performance bottlenecks.
  • Breaking down large functions into smaller, more manageable ones.

A 4-Step Workflow for AI-Assisted Refactoring

Never just paste your code and ask "make this better." A structured approach yields far better results and is much safer.

Step 1: Ensure Your Code Works and is Version Controlled. Before you change anything, confirm your code works as expected. Have a set of tests you can run. Most importantly, commit your working code to a version control system like Git. This gives you a safe checkpoint to return to if the refactoring goes wrong.

Step 2: Isolate a Small Piece of Code. Don't give the LLM your entire application. Feed it one function or one class at a time. This provides more focused context and results in better, more manageable suggestions.

Step 3: Craft a Specific Prompt. Provide the isolated code and a clear, specific goal. Use the persona pattern to guide the model. For example: "Act as an expert Python developer. Here is a function I wrote. Please refactor it to be more Pythonic and add a descriptive docstring."

Step 4: Review, Understand, and Test. This is the most important step. Do not blindly copy and paste the LLM's output. Read through the suggested changes. Do you understand why it made them? If not, ask it to explain. Then, integrate the new code into your project and run your tests to ensure nothing has broken.

Prompting Techniques for Specific Goals

For Readability and Simplicity

"Review this code for readability. Can any part of it be simplified? Are the variable names clear?"

For Idiomatic Code

"Please refactor this Python code to be more 'Pythonic.' Use list comprehensions and other idioms where appropriate."

For Documentation

"Generate a Google-style docstring for this function. Explain what the function does, its arguments, and what it returns."

For Performance

"Analyze this function for performance bottlenecks. Is there a more efficient way to accomplish this task? Explain your reasoning."

The Final Step: Human Review and Testing

An LLM is a powerful assistant, not an infallible oracle. It can introduce subtle bugs, misunderstand the original intent of the code, or make stylistic changes you don't agree with. You are the developer, and you have the final say.

Always ask yourself:

  • Is the new code genuinely easier to read?
  • Do I understand what every line of the new code does?
  • Does it still pass all my tests?
  • Does it handle edge cases correctly?

If the answer to any of these is no, either discard the suggestion or ask the LLM to refine it with more context.

Frequently Asked Questions

Should I let an AI write my code from scratch?

While LLMs can write code from scratch, they are often more effective as refactoring tools. Starting with your own working logic and using the AI to improve it keeps you in control and ensures the code meets your specific requirements.

Is it safe to paste my company's code into an LLM?

You must check your company's policy. Pasting proprietary code into public AI tools is often a security risk and may be against company rules. Use local, on-device models or enterprise-grade AI platforms with strict data privacy controls for sensitive code.

What if I don't understand the LLM's suggestion?

Ask for an explanation! Treat it like a tutor. A great follow-up prompt is: "Can you explain the difference between my original code and your suggestion, and why your version is better?"

Key Takeaways

  • Code refactoring improves the quality of working code without changing its function.
  • LLMs excel at refactoring because they are trained on vast amounts of high-quality code.
  • Use a structured workflow: start with working, version-controlled code, and refactor one small piece at a time.
  • Craft specific prompts that target clear goals like readability, performance, or documentation.
  • Never trust the LLM's output blindly. Always review, understand, and thoroughly test the suggested changes.

Related Reading

  • How to Force an LLM to Generate Perfect JSON Every Time
  • The Persona Pattern: How to Make an LLM Your Expert Co-Worker
  • What Is Function Calling? How LLMs Use Tools to Get Live Data

Tagsberulearning