Legacy Code: Wrap a method

I’m a big fan of Michael Feathers’s book Working Effectively With Legacy Code, and now and then I reread it because there’s always something to refresh or remind me.

Right now I’m looking at the “Wrap Method (67)” technique. It’s really simple. I’m just restating it here.

Suppose you have a crufty, untested method called Foo. You need to change it by adding some “bar” functionality. You’re not on a mission to retrofit the legacy code for testing, but you do want all new code to be conformant. So here’s what you do:

class Aces
{
  void Foo()
  {
    // existing untestable stuff
  }
  void Bar()
  {
    // awesomely testable code
  }
  void FooAndBar()
  {
    Foo();
    Bar();
  }
}

The great thing about this is that you can come back on a later refactoring run to make Foo testable, then collapse it back into one method if that’s what you prefer then. Meanwhile, you are keeping new code reliable by not mixing it up with unreliable code.

Leave a Reply

Your email address will not be published. Required fields are marked *