Debugging and Refactoring with Cursor
Learn how to use Cursor’s AI assistant to identify bugs, suggest fixes, and refactor messy code into clean, maintainable functions.
In this lesson, we’ will explore how Cursor helps us debug and refactor existing code. We’re intentionally starting with a simple example to concentrate on learning how to use Cursor’s features effectively. The objective is to build confidence in the workflow and tools before we advance to a more complex project later.
We’ll use Cursor to:
Identify and fix runtime errors or faulty logic.
Detect bad practices like redundant code or inconsistent naming.
Break down large functions into smaller, cleaner parts.
Apply standard refactoring techniques to improve structure and maintainability.
Locate relevant logic using both keyword and semantic search.
Debugging and refactoring are part of the natural development process, and Cursor is designed to support both. By selecting code, submitting prompts, and reviewing suggestions, we can improve code quality while staying focused on the broader task.
Starting with a buggy script
Let’s say we’re handed a simple script that is meant to calculate the average of even numbers in a list. At first glance, it looks functional, but when we try to run it, we encounter a runtime error.
Here’s the original code:
def get_even_average(numbers):total = 0count = 0for num in numbers:if num % 2 == 0:total = total + numcount = count + 1else:continueif count == 0:return 0return total / countdef main():data = [1, 2, 3, 4, 5, 6, 7, 8]average = get_even_average(data)print("The average is: " + average)main()
We run the script using the integrated terminal in Cursor. As expected, it throws an error, TypeError: can only concatenate str (not "float") to str
:
This error occurs because the code tries to concatenate a string with a float using the +
operator, which is not allowed in Python. Next, we’ll use Cursor to fix this issue and then continue improving the structure of the code through refactoring.
Fixing the runtime error with Cursor
To begin debugging, we highlight the part of the code that triggered the error. In this case, it’s the print
statement inside the main()
function:
print("The average is: " + average)
With this line selected, we open Cursor’s chat and type a prompt like:
Prompt: This line causes a
TypeError
. Can you fix it?
Cursor reviews the selected code and uses the prompt to generate a suggested fix. Here’s the response: