How to Debug Code Step by Step
Debugging feels like guessing until you give it a process. Experienced developers aren't smarter at it. They follow a routine, and so can you.
Reproduce it
Find the exact steps that cause the problem, and make sure it happens every time. A bug you can trigger on demand is half solved.
Read the error message properly
Read it from the top. Note the file name, the line number and the first line of the message. The most useful clue is usually there, and many people skip it.
Make the problem smaller
Remove code until the bug disappears, then put back the last piece. Or comment out half the program and see which half still fails. Shrinking the problem shows where it lives.
Check your assumptions
Print out the values at the points you are sure about. Most bugs are a variable that holds something different from what you believed.
Change one thing at a time
If you change three things and it works, you don't know which one fixed it. Make a single change, test, and write down the result.
Use version control
Commit working states so you can go back. Seeing exactly what changed since the last working version often points straight at the cause.
Ask a clear question
If you're stuck, explain the problem to a person or to a code explainer: what you expected, what happened, the error message and the smallest code that shows it. Writing it out often reveals the answer before you send it.
Understand the fix
Don't paste a fix you can't explain. Ask for a line-by-line explanation, so the same bug doesn't come back next week.
Try it: Paste your code into Explain and debug in Studio and ask what each part does. Open the tools. Everything the tools produce is a first draft. Check it before you use it.
