Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Refactoring copy-pasted code

by ELISHEVA (Prior)
on May 04, 2009 at 18:40 UTC ( #761792=note: print w/replies, xml ) Need Help??

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

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://761792]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2023-06-05 00:14 GMT
Find Nodes?
    Voting Booth?
    How often do you go to conferences?

    Results (22 votes). Check out past polls.