Split Message Chain
Examine
What you’re looking for is code that has chained dependencies - it talks to a “friend’s friend”. A “friend” is a parameter of the current method, an object you constructed, or an attribute of the current class. Identify which object is the “friend” that you are ok to talk to, but that gives you access to other objects that you don’t want to depend on directly.
The unwanted dependency could be obvious if you have a clear Message Chain, like A.getB().getC(). In that example the “friend” is A, and the “friend’s friend” is the thing returned by “A.getB()”.
Prepare
If you don’t have a variable for the “friend” object, create one using Introduce variable.
Implement
- Extract method on the section of code containing the dependency. One of the arguments to the new method must be the “friend” - usually the variable you just introduced
- Move method - to the “friend” class
- Test.
Clear
- Check if you should inline the variable you introduced in the prepare step.
Follow up
- Go to the new method in the “friend” class. It may have further message chains that you can treat in the same way.
Prompted by Code Smells
Relevant Learning Hours
Sources
- This refactoring was contributed to this site by Emily Bache
Back to All Refactorings