2 min read

Debugging Techniques

Debugging is the process of identifying and removing errors from computer hardware or software. It is a core skill for any programmer, often taking more time than writing the initial code.

1. Print Debugging

The simplest and most common technique. You insert print statements (or logging) at critical points in your code to track the flow of execution and the state of variables.

  • Pros: Easy to implement, works in almost any environment.
  • Cons: Can clutter code, requires cleanup, requires re-running the program.
def calculate_total(price, tax):
    print(f"DEBUG: price={price}, tax={tax}") # Debug print
    return price + (price * tax)

2. Rubber Duck Debugging

A method where you explain your code, line-by-line, to an inanimate object (traditionally a rubber duck).

  • Why it works: Forcing yourself to articulate the logic often reveals the discrepancy between what you thought you wrote and what you actually wrote.

3. Using a Debugger

Modern IDEs (VS Code, IntelliJ, PyCharm) come with powerful interactive debuggers.

  • Breakpoints: Pause execution at a specific line.
  • Stepping: Move through code one line at a time (Step Over, Step Into, Step Out).
  • Watch Window: Monitor specific variables as they change in real-time.
  • Call Stack: See the chain of function calls that led to the current point.

4. Binary Search (Divide and Conquer)

If you have a large block of code or a large dataset causing a crash, try to isolate the issue by splitting the problem in half.

  1. Comment out half the code (or remove half the input data).
  2. Does it still crash?
    • Yes: The bug is in the active half.
    • No: The bug is in the commented-out half.
  3. Repeat until the offending line is found.

5. Static Analysis (Linting)

Tools that analyze your code without running it. They can catch syntax errors, type mismatches, and potential bugs early.

  • JavaScript: ESLint
  • Python: Pylint, Flake8, MyPy
  • Java: Checkstyle, FindBugs

programming/error-handling programming/common-syntax