Reduce Stress, Write a Test
By: Mike Clark
Summary: All code is not created equal. Learn from a master of the craft how to spot bad code and mold it into good. This month, Mike Clark explains how writing automated tests can give you confidence to change code fearlessly.
Let's take stock of our progress. So far we've been practicing craft techniques that help keep code responsive to change: choosing good names and making the code expressive. If only it were that easy. The next person faced with modifying the code—to fix a bug, add a feature, etc.—may appreciate our efforts, but clean, well-documented code simply isn't enough.
Here's the rub: Pristine code is still bad code if we don't have the confidence to modify it predictably. Every time you touch the code a cold chill runs up your spine and your typing fingers tremble with fear. You've been
bitten before—an innocent change here unknowingly breaks something over there, and what you thought would take mere minutes has turned into several painstaking hours. And so the police tape is strung permanently around the code, workarounds are used to avoid losing one's sanity, and before long what once was the cleanest code on the project has decayed into the nastiest code imaginable.
It doesn't have to be this way. Automated tests drive out fear and give you confidence to change code with impunity. While it may seem like writing tests will slow you down, you actually end up delivering higher quality software—and faster. So before we go any further, let's start writing some tests.
Got a Test for That?
Say you're working on a digital music player. Among other things, it lets you add your favorite songs to a playlist.
It can tell you how long you could listen to the playlist without a song repeating. (Hey, it's a full-featured player.) Here's the Java code that makes all that magic possible:
... to read more articles, visit http://sqa.fyicenter.com/art/