Friday, 15 June 2012

Refactoring with WinMerge

A short post which I thought I would share since I found it useful.

The other day I was looking at some code and I knew that two functions were written in a very similar way, so I wanted to refactor them into just one function. But how do you see how similar they are? You could do it by eye, but there could be human error. Surely a better way is to have the two functions side by side so you can see the differences. And what do you know, there are tools out there that are designed to do just that.

So here is what I did:

  1. Copy the two functions into two separate temporary files.
  2. Compare those two files with WinMerge (or your favourite diff tool).
  3. Immediately see what's similar and what is different. Here's what I saw:

I can now see that a lot of it is very similar, giving me some indication of how I could refactor them into one function.

Sometimes the simplest solutions are the best. 

No comments:

Post a Comment