http://qs1969.pair.com?node_id=761792


in reply to Refactoring copy-pasted code

There are many ways to do this, but this is how I might go about it:

  1. Make sure all scripts are under version control.
  2. Develop a set of unit tests for one of the three scripts so you have a way of verifying that you haven't broken anything. Make sure the tests cover all of the major functionality that must not break.
  3. Study the code in all three making notes of all the places where there are differences. To get an idea of where to focus your attention you might use the shell command diff to compare the files.
  4. First refactoring pass:
    1. design/declare a data structure to hold all of the differences. This obviously will include some data. However, you may notice that there are bits of flow of control that also differ. If so, write a subroutine that encapsulates those bits and put a code reference into your data structure.
    2. refactor the script for which you wrote the test suite so that it uses the data structure you designed in the previous step.
    3. run your test suite to make sure that the refactoring broken nothing
  5. Second refactoring pass:
    1. define a class. The data for objects in the class will be the data structure. The methods will be the functions in that first script. The parameters to the new method will be the data that populates that structure.
    2. refactor again so that the first script simply creates the object and calls its run method
    3. test again
  6. For the remaining scripts:
    1. write a test suite. If the outputs are similar enough (e.g. only input-expectation pairs change). You may find it easier just to expand the first test suite so that it can be used to work with more than one script.
    2. refactor the script so that it creates an object and runs it
    3. test

If you are really comfortable with objects and refactoring you may be able to get away with merging the two refactoring phases into one (I usually do). I included them separately because I think I mentally go through both those phases even if I only code the second one.

Best, beth