How to write your automated tests so they don’t fail when you refactor

The main benefit of a good automated test suite is that it gives you confidence that your code is working correctly.  It helps you find bugs as soon as you introduce them instead of at 3am on a production environment.

If you have a solid test suite, you can feel confident that the change you made is safe.  When you have that confidence, it allows you to change the nastiest parts of your code without wondering if you broke something.

But sometimes tests can get in your way.  Sometimes you’ll want to refactor a group of classes and tests will fail even though nothing actually broke.  This is a bad smell and it should be avoided.  In this article I’m going to teach you how.  But, before I do that, I want to make sure we all agree on the definition of “refactoring”.

Code refactoring is the process of restructuring existing computer code – changing the factoring – without changing its external behavior. –Wikipedia

In other words, refactoring means cleaning up the code without changing functionality.  If you refactored correctly, every single feature in your application should work exactly the same as it did before you refactored.

Here’s how you know you’ve got a problem

Continue reading

Banning break and continue from your loops will improve code quality

For as long as I can remember programming, I have always avoided the  break  and continue  keywords in my loops.  Before I explain why I avoid them, I want to explain what they are.  Here’s an example:

A continue  will jump to the top of the loop and reevaluate the condition.  A break  will exit the loop.

What I don’t like about these keywords is that when you want to refactor this code, the continue s and break s step on your toes.  Here’s an animated GIF demonstrating why that is:

Continue reading