Multi-file search and replace: replacefromfile.py

The code editor we use lacks support for multi-file search and replace, and this makes renaming a method or class a lot more work-intensive than if such IDE support were there. Recently I needed to do several such renames. My work started out as modifications and additions to one large multipurpose class, but I noticed that I was adding still more responsibilities to the class. The class’s methods already showed that it had multiple natures: CreateA, ModifyA, DeleteA, CreateB, ModifyB, etc. I was adding methods to deal with C’s and D’s as well.

I didn’t refactor first off, though, because the class was not under test yet. I was afraid that during the process of renaming I might break something and not know it. So the first step I took was to write a unit test for the class. Next, I added in all my new methods for dealing with C’s and D’s into the multipurpose class (looking back, I think I wasted time by doing this, as it increased the amount of renaming I would need to do later, but I did not see this at the time), and wrote unit tests for them.

Now, with everything under basic test, I felt more confident to move methods out to their new classes. I created an A class and moved the CreateA, ModifyA, and DeleteA methods in there. Then I was able to rename the methods to just Create, Modify, and Delete, since it was now clear what kind of thing they operated on.

The remaining step was to replace all references to the old class name and method names with the new class names and method names. To do this, I wrote a Python script that would take a file containing search strings and replacement strings and do the replacements. I then created my replacements file containing lines like this (though actually there were about twenty replacements):

CreateA Create
ModifyA Modify
DeleteA Delete

Then I exported my source code project as XML (a trick I learned from Aaron Alexander – thanks, Aaron!) and ran my replace utility like this:

python replacefromfile.py –replacements-file=replacements.txt < myproject.xml > changed.xml

Then I re-ran my tests. If I recall correctly, they still passed.


replacefromfile.py.txt

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s