When starting out in software development or even learning a new language as an experienced developer, the most likely cause of most ‘I don’t know why this code isn’t working’ type questions is pretty simple:
What you think your code should be doing is often not what it’s actually doing.
This seems like an obvious observation, but it’s easy for even an experienced developer to get caught up in what they think their code is doing, and they forget to look at what it’s actually doing.
Next question: “ok, so how do I find out what my code is actually doing at runtime?”
Answer: you use a debugger. You step through your code and you compare what you think each line should be doing with what it’s actually doing. At some point you’ll find a line where you assumed the code was doing one thing but it’s actually doing something else. It could be the variable of a value that you were assuming to be a particular value but actually it’s something different and it results in a result that’s different from what you were expecting. It could be a condition you were assuming to be true is actually false. It could be a block you were assuming would always get executed but never is. There’s many reasons.
Learn how to use your debugger:
- Practice stepping through your code
- Learn how to set breakpoints
- Learn how to set conditional breakpoints (break when a certain value or condition is met)
- Learn how to inspect value of your variables
- Learn how to change values at runtime – what happens when this value is 1 instead of 2?
- Learn to break on an error
- Learn how to step backwards to a previous statement (not all debuggers do this but it’s a useful feature)
- Learn how to change code while you’re debugging
Knowing how to use a debugger is an incredibly valuable skill. It’s seems a given that as a developer you would learn to use and use a debugger as an integral part of your development, but all too often though when asked ‘why is this code not working’, if you ask ‘have you stepped through in a debugger to see why it’s not working?’ the answer is ‘no’.
Learn to use your debugger!