Split Phase

This is one of the refactorings in Martin Fowler’s book. Often this refactoring opens up for a lot of other useful changes.

Examine

Look for one section of code that is doing two separate things - ie you have Divergent Change.

Prepare

Identify the two concerns you want to split. You may need to do some ‘introduce variable’ refactorings and ‘slide statement’ refactorings to gather all the relevant parts together. Aim for two sections of code that each do one thing. There will probably be a number of variables which are calculated in the first section and used in the second section.

Implement

Clear

Adjust names for classes and variables - something better than ‘LocalData’.

Follow up

It often makes sense to Extract methods for the first and second sections - the return type of the first method is LocalData, the argument to the second is LocalData.

If the two sections of code are in the same loop, you should now split it. There is a useful trick for making this easier:

Now split the loop:

At this point the code is broken because there are references to ‘localData’ in the second loop.

Often you now want to turn both loops into pipelines, and/or start making LocalData into a proper domain class and moving methods to it.

Prompted by Code Smells

Relevant Learning Hours

Sources

Back to All Refactorings