Realise that you have a bug
If you’re reading this chapter, you’ve probably already completed this step. It is a surprisingly important one: you can’t fix a bug until you know it exists. This is one reason why automated test suites are important when producing high-quality code.
Make it repeatable
Once you’ve determined you have a bug, you need to be able to reproduce it on command. Without this, it becomes extremely difficult to isolate its cause and to confirm that you’ve successfully fixed it.
Generally, you will start with a big block of code that you know causes the error and then slowly whittle it down to get to the smallest possible snippet that still causes the error. Binary search is particularly useful for this. To do a binary search, you repeatedly remove half of the code until you find the bug. This is fast because, with each step, you reduce the amount of code to look through by half.
If it takes a long time to generate the bug, it’s also worthwhile to figure out how to generate it faster. The quicker you can do this, the quicker you can figure out the cause.
As you work on creating a minimal example, you’ll also discover similar inputs that don’t trigger the bug. Make note of them: they will be helpful when diagnosing the cause of the bug.
If you’re using automated testing, this is also a good time to create an automated test case. If your existing test coverage is low, take the opportunity to add some nearby tests to ensure that existing good behaviour is preserved. This reduces the chances of creating a new bug.
Figure out where it is
If you’re lucky, one of the tools in the following section will help you to quickly identify the line of code that’s causing the bug. Usually, however, you’ll have to think a bit more about the problem. It’s a great idea to adopt the scientific method. Generate hypotheses, design experiments to test them, and record your results. This may seem like a lot of work, but a systematic approach will end up saving you time. I often waste a lot of time relying on my intuition to solve a bug (“oh, it must be an off-by-one error, so I’ll just subtract 1 here”), when I would have been better off taking a systematic approach.
Fix it and test it
Once you’ve found the bug, you need to figure out how to fix it and to check that the fix actually worked. Again, it’s very useful to have automated tests in place. Not only does this help to ensure that you’ve actually fixed the bug, it also helps to ensure you haven’t introduced any new bugs in the process. In the absence of automated tests, make sure to carefully record the correct output, and check against the inputs that previously failed.
Content will be erased after question is completed.