Chapter 18. Testing and Debugging

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

Brian Kernighan

Most people recognize that testing and debugging are somehow related; that debugging is the natural consequence of testing, and that testing is a natural tool during debugging.

But, when used correctly, testing and debugging are actually antagonistic: the better your testing, the less you'll need to debug. Better testing habits repay themselves many times over, by reducing the effort required to diagnose, locate, and fix bugs.

Testing and debugging are huge topics, and a single chapter like this can only outline the simplest and most universal practices. For much deeper explorations of the possibilities, see Perl Testing: A Developer's Notebook (O'Reilly, 2005), Perl Debugged (Addison Wesley, 2001), and Perl Medic (Addison Wesley, 2004).

Test Cases

Write the test cases first.

Probably the single best practice in all of software development is writing your test suite first.

A test suite is an executable, self-verifying specification of the behaviour of a piece of software. If you have a test suite, you can—at any point in the development process—verify that the code works as expected. If you have a test suite, you can—after any changes during the maintenance cycle—verify that the code is still working as expected.

So write the tests first. Write them as soon as ...

Get Perl Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.