Replace Function with Command - Static to Instance

This is one of the refactorings in Martin Fowler’s book. The basic idea is to change a freestanding function into a method on a class. In languages like Java and C# you’d probably call it ‘static to instance’. This is the inverse of Replace Command with Function

Examine

Usually the prompt for this refactoring is a need for more flexibility - a method can be overridden in a subclass, it can remember state between invocations, and you can combine it with other methods to make a better overall abstraction. Freestanding functions can have a ‘feature envy’ code smell with respect to a parameter, and might make more sense to become a method on that parameter’s class.

Prepare

Identify the function you want to turn into a command - that is, a method on an object. Identify whether the class it should be moved to exists already and if not, create it.

Implement

Alternative to Introduce Parameter

Some refactoring tools don’t offer this, but you can achieve the same result as long as you have ‘extract method’ and ‘inline method’, which are more widely supported.

Clear

Check if there are any unnecessary arguments or variables that should be inlined.

Follow up

Check whether the method can take advantage of OO design structures, like polymorphism.

Prompted by Code Smells

Relevant Learning Hours

Sources

Back to All Refactorings