8 Debugging and better understanding your code

 

This chapter covers

  • Determining the source of a bug
  • Fixing errors with Copilot techniques
  • Debugging code with Copilot
  • Using VS Code debugger to see how code is functioning

There will be a point in every programmer’s career when their code isn’t doing what they want it to do. This has likely happened to you already, and, rest assured, it is a normal part of learning to program. How do we fix the code? Sometimes, changing the prompt or better decomposing the problem like you learned in earlier chapters is sufficient to fix the problem. But what do you do when you just can’t get Copilot to give you different or better code and you can’t seem to figure out why the code you’ve been given doesn’t work properly?

This chapter serves two purposes. The primary goal is to learn how to find errors (called bugs) in the code and fix them. To find those bugs, you’ll need to fulfill the second goal, which is gaining a deeper understanding of how your code works while you are running it.

The good news is that having an error in your code is such a common occurrence for programmers that programming environments, like Visual Studio Code (VS Code), have tools to help us uncover what is going wrong. We’ll learn how to use that tool, called a debugger, in this chapter as well.

8.1 What causes errors (bugs)?

8.2 How to find the bug

8.2.1 Using print statements to learn about the code behavior

8.2.2 Using VS Code’s debugger to learn about the code behavior

8.3 How to fix a bug (once found)

8.3.1 Asking Copilot to fix your bug via chat

8.3.2 Giving Copilot a new prompt for the whole function

8.3.3 Giving Copilot a targeted prompt for part of a function

8.3.4 Modifying the code to fix the bug yourself

8.4 Modifying our workflow in light of our new skills

8.5 Applying our debugging skills to a new problem

8.6 Using the debugger to better understand code

8.7 A caution about debugging

Summary