Look at Cloned Code Feature in Visual Studio 2012

In this article, we will look into one of the new features of Visual Studio 2012 for determining duplicate code within an application. The Cloned Code feature helps us to determine any duplicates or similar code within the application, that helps us to refactor that code and reduce code maintainability. Let's open Visual Studio 2012 and open our existing project (or) create a sample MVC 4 internet application.

Add the following piece of code in Home Controller:

In Index action

object ob = null;

if (ob == null)

{

    ob = new object();

    int code = 0;

    Type t;

    if (ob.ToString() == "test")

    {

        code = ob.GetHashCode();

    }

    else

    {

        t = ob.GetType();

    }

               

}

In About and Contact action

object myOb = null;

if (myOb == null)

{

    myOb = new object();

    int code = 0;

    Type t;

    if (myOb.ToString() != "test")

    {

        t = myOb.GetType();

    }

    else

    {

        code = myOb.GetHashCode();

    }

}

Select the cloned code and click on "Find Matching Clones in Solution" as shown below:

Look-Cloned1.jpg

We can see the results of it in the following window:

Look-Cloned2.jpg

We can even compare the differences between the cloned codes using the Compare option:

Look-Cloned3.jpg

The Cloned Code feature is based on code semantics and not just simple text comparison. It can find duplicate code when the variable names vary or the order of statements in the code varies.

We can find all the cloned code segments within our solution by going to "ANALYZE" -> "Analyze solution for Code Clones" as shown below:

Look-Cloned4.jpg

This will show all code clones having more than 10 lines of code within the solution in the Code Clone Search Results as shown below:

Look-Cloned5.jpg

Depending on the level of duplication in code, results will be split into Exact Match, Medium and Weak Match.

We can use this feature to find all duplicate code segments within any .NET project and refactor it accordingly.
 

Up Next
    Ebook Download
    View all
    Learn
    View all