sensing variables


Getting Serious about Preserving Behavior
is a great little article by Mike feathers, in which he introduces a refactoring trick he calls sensing variables. The gist is this:

You want to refactor some code, but it’s too ugly to test as it currently stands. So there’s a danger that the refactoring will somehow inadvertently change behaviour. Mike suggestes introducing a new variable outside of the scope of the code under test, and then altering the code to report state into that variable. Now, write tests that check the values in the variable, under a variety of conditions. Those tests will tell us whether our subsequent refactorings have changed the variable’s value – in other words, whether we have accidentally changed some deep behaviour somewhere. Very nice.

(The technique is also covered in Mike’s book Working Effectively with Legacy Code – see Chapter 22 “I Need to Change a Monster Method and I Can’t Write Tests for It”)

About these ads

One thought on “sensing variables

  1. As a related thing, I once wrote perl’s Devel::Spy which is a logging proxy object. The idea is, write an object that is transparent for some input to the monster method and get it to report back on what happened to it. For more points, have your proxy also wrap its outputs and establish a chain of events for each value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s