Legacy Code Change Algorithm
When working with legacy code, it is very easy to get carried away and make a big bang refactoring (actually, 'code cleanup and pray' is a better term since we do not have any tests). In this case, we can try to eliminate the static cling by making the static method non static, and extracting the non-static method into an interface. Make the clients (all the call sites) use the interface. This would mean that we deal with potentially a few changes to the client code to a few hundreds in some worst case scenarios, all at one time. The result could be 'Object Reference not set to an instance of an object'. We want to be able to make this change in a phased manner in small manageable increments.
Approach
- Pick one call site.
- Change in one call site.
- Bring it under the safety net of unit tests.
- Make sure the change works.
- Meanwhile, the other call sites continue using the original unchanged code and continue to work fine.
- Go back to step 1 till all the call sites are refactored, and remove the static method finally.
Introduce Instance Delegator
- If the class which contains the static method is static, make it non static.
- Introduce an instance method with the same signature which delegates to the static method.
- Use ExtractInterface and extract the instance method created.
- At the call site for the static method, change to use the instance method (called through the extracted interface) instead of the static method.
- The instance can be provided at the call site
- as a parameter
- via setter injection
- via constructor injection
Comments
Post a Comment