Problems with Copy Pasting Code - And Modifying Slightly... Then How To Go Back And Fix It All Up Afterwards.

As developers, we often find ourselves under a lot of pressure to crank out code and copy then paste it somewhere else in a solution and make a slight modification here and there and get the product out the door. It's a frequent occurrence and hence the number of lines of code is not a great measure of quality code. There's nothing wrong if it gets the code out the door, however, when we have time we can go back and fix this.

What happens, if we don't and some code has been copied and pasted in different renditions and a bug comes up in one of the scenarios? We can fix it in the one instance, but that bug may also be applicable in all or some the copy/paste instances of code.

Considering the frequency of these scenarios, we've introduced Code Clone Analysis in Visual Studio 2012. What is does it search a solution and looks for similar code.

From the Analyze menu in Visual Studio 2012, we select "Analyze Solution for Code Clones"

We the observe that in this case we have two strong matches.

 Let's select both the files and compare as shown below...

 

We can see below that the methods are very similar. This is an opportunity to refactor. Perhaps to turn this into a single method, with some extra parameter or some class redesign or perhaps to use generics.

In fact you can select a piece of code and select "Find Matching Clones in Solution" from the context menu as shown below.

So, when you get a chance, like a couple of minutes, check out the tool and see how much copying and pasting has been going on in your team ;)