透明思考


Transparent Thoughts


Break Out a Method Object (From a Monster Method)

(From the bookWorkingEffectively with Legacy Code)

Sensing variablesare very powerful tools in our arsenal, but sometimes you notice that you already have variablesthat 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 instancevariables, but, in many cases, that can be confusing. The state that you put there will be commononly to the monster method and the methods that you extract from it. Although it will bereinitialized every time the monster method is called, it can be hard to understand what thevariables will hold if you want to call methods that you’ve extracted independently.

One alternative isBreak Out Method Object (330). This technique was first described by WardCunningham, and it epitomizes the idea of an invented abstraction. When you break out a methodobject, you create a class whose only responsibility is to do the work of your monster method. Theparameters of the method become parameters to a constructor on the new class, and the code of themonster method can go into a method namedrunorexecuteon the new class. When the code has been moved to the new class, we’re in a great position torefactor. We can turn the temporary variables in the method into instance variables and sensethrough them as we break down the method.

Breaking out a method object is a pretty drastic move, but unlike introducing a sensing variable, thevariables that you are using are needed for production. This allows you to build up tests that youcan keep. SeeBreak Out Method Object (330)for a detailed example.