Debugging
Your code doesn’t always run as you intend it to—and that’s okay! One of the most important parts of programming is figuring out why your code isn’t working and how you can fix these problems (programmers call these ‘bugs’). This process is referred to as “debugging”.
Common problems you might encounter are:
- Accidental mistakes — We all make mistakes! Making mistakes is an important part of learning. Here’s a list of common problems that you can use to watch out for:
- Typos — putting the wrong number or wrong variable
- Moving code around by accident
- Logic errors — These are bugs that are caused by not understanding how something will work.
Coding is all about trial and error. For example, you might have planned out your code to solve a problem by using one particular approach. But then, you find out that approach doesn’t actually work correctly, or doesn’t work under particular circumstances.
Here are some general tips for debugging:
- Ask yourself what you want to happen when you play your project, and compare it to what is actually happening when you play the project.
- When is the problem happening? Does it happen after you do a specific action? Try replicating the issue to help narrow down where this issue might be happening in your code.
- Once you have a better idea of where the problem is, go through your code, block by block, and predict exactly what you expect the block will do. Is it the same as what you want to happen?
- Check the order of your blocks. They will run exactly in the order that they are placed.
Here’s a tip when debugging with variables:
It’s helpful to see the values of your variables appear as you play your project. This way, you can check if a variable has the value you’re expecting it to have.
You can do this by using a Text object, and adding a magenta “When Game is Playing” block. Inside the magenta when block, add a “Set Text” block. Tap the gray parameters icon to get to your variables. Then, set it to the variable you’re wanting to monitor. (For example, if you expect it a variable to increase by 10 when the iPad is tapped, you will be able to see the variable increase by 10.)
If you have a lot of text objects displaying variables, you can use a purple Add bubble include the name of the variable, like this:
This will display a result like this, in Play Mode:
Sometimes it might also be easier to try another solution to work around the problem, if you can’t fix the exact cause of the problem directly.