Break Out a Method Object (From a Monster Method)
October 21st, 2007
(From the book Working Effectively with Legacy Code )
Sensing variables are very powerful tools in our arsenal, but sometimes you notice that you already have variables that would be ideal for sensing but that are local to the method. If they were instance variables, you could sense through them after a method runs. You can turn local variables into instance variables, but, in many cases, that can be confusing. The state that you put there will be common only to the monster method and the methods that you extract from it. Although it will be reinitialized every time the monster method is called, it can be hard to understand what the variables will hold if you want to call methods that you’ve extracted independently.
One alternative is Break Out Method Object (330). This technique was first described by Ward Cunningham, and it epitomizes the idea of an invented abstraction. When you break out a method object, you create a class whose only responsibility is to do the work of your monster method. The parameters of the method become parameters to a constructor on the new class, and the code of the monster method can go into a method named run or execute on the new class. When the code has been moved to the new class, we’re in a great position to refactor. We can turn the temporary variables in the method into instance variables and sense through them as we break down the method.
Breaking out a method object is a pretty drastic move, but unlike introducing a sensing variable, the variables that you are using are needed for production. This allows you to build up tests that you can keep. See Break Out Method Object (330) for a detailed example.
The Legacy Code Change Algorithm
October 15th, 2007
(From the book Working Effectively with Legacy Code )
When you have to make a change in a legacy code base, here is an algorithm you can use.
1. Identify change points.
2. Find test points.
3. Break dependencies.
4. Write tests.
5. Make changes and refactor.
What Is Legacy Code
October 15th, 2007
(From the book Working Effectively with Legacy Code )
To me, legacy code is simply code without tests. I’ve gotten some grief for this definition. What do tests have to do with whether code is bad? To me, the answer is straightforward, and it is a point that I elaborate throughout the book:
Code without tests is bad code. It doesn’t matter how well written it is; it doesn’t matter how pretty or object-oriented or well-encapsulated it is. With tests, we can change the behavior of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse.



