Refactoring : Clean Code using Resharper And Stylecop

Background

I have been using Resharper for past few months. Over a period of time I have become a big fan of this refactoring tool. Now I realize why many people can’t work without Resharper. The productivity improvements you get using this are really good. I would like to thank guys from ThoughtWorks who introduced us to this tool. It has really helped my team ever since we started using it. In this post I am going to demonstrate how we can make use of Resharper and StyleCop to improve the quality of code.

 

Advantages of using Resharper

Some of the benefits I see in using Resharper is its able to highlight issues with code like

  • Highlight Unused Using statements.
  • Find unused members of a class like Methods, Properties and Variables.
  • Suggestions like converting a LINQ expression into a Lambda expression.
  • While using String.Format method, Resharper can validate that the placeholders match the supplied values.
  • While using logical constructs like If Else it can suggest better options like ?:
  • When using multiple if statements it can Refactor into a Switch case loop.
  • With methods which return values, and if we are using If Else construct to return two different values based on certain conditions then Resharper can suggest changes to redundant else conditions.
  • Based on the usage of methods, Reshaper can suggest to change the methods to static methods or even the variables to readonly variable.

These are very minimal features of Resharper. I don’t want to reinvent the wheel in documenting them. You can visit the Resharper documentation to find out more details about the capabilities of this indispensible tool for any developer.

 

StyleCop for Resharper Addin

There are many plug-ins available for Resharper. You can find out about various plug-ins on the Resharper website. One plug-in which I have been using extensively is the StyleCop for Resharper. StyleCop is a Microsoft tool for validating the code for conformance to standards and best practices. It parses the source code in each file and identifies the lines of code which does not follow the various rules defined by Microsoft. These rules are similar to the ones defined in the FxCop. The main difference is FxCop analyzes the compiled code while StyleCop is used for analyzing the source code.

StyleCop can analyze source code for various rules which can be classified into

  • Documentation Rules
  • Layout Rules
  • Maintainability Rules
  • Naming Rules
  • Ordering Rules
  • Readability Rules
  • Spacing Rules

You can see these in the screenshot below

stylecop categories

To know about each rule which falls under these categories I would suggest you look at the StyleCop documentation. Installing StyleCop plugin for Resharper is pretty simple. You just download a zip file and run a batch file to register the plugin. Now you get the power of Resharper and StyleCop right inside Visual Studio IDE. Instead of wasting too much time talking about these tools lets get started with the action.

 

Code containing StyleCop And Resharper warning

Let me implement a class which ahs many of the commonly displayed warning and suggestions by both these tools in VS 2010 IDE.

public class ClassWithWarnings
{
    private string _name;

    public string Name
    {
        set { _name = value; }

        get { return _name; }
    }

    public ClassWithWarnings()
    {

    }

    private void DummyMethod()
    {
        Console.WriteLine("This method does nothing");
    }

    public ClassWithWarnings(string input)
    {

        Console.WriteLine(input);

    }
}


Because of the stylesheet of my blog you might not be able to see each and every warning highlighted in the above code. I would suggest you download the trial version of Resharper if you don’t have a copy and add StyleCop plugin to see how it works.



You can move the mouse pointer over each warning to find out more details about it. You can also use F12 to move to the next error or warning if you are using the shortcut keys mapped to the Resharper shortcuts. Once you hit F12 it will navigate to the next possible error or warning and you can hit Alt + Enter to get the available options to refactor the code. This is helpful if there are only very few errors and warning in the file. But it becomes quite boring to keep pressing the above combinations and resolve each error individually. And some of the warning are very trivial that they can be automatically sorted out like removing unused usings and ordering them in correctly.



Resharper and the StyleCop plugin comes to the rescue once again. It has an option called Cleanup code which we can access by right clicking on any class file in the Solution Explorer window



clean up code menu



Selecting this option pops up another window which by default has two profiles created for us




  • Full Cleanup


  • Reformat code



You can select each profile to see what all settings it can apply for us to the code if we run code cleaup activity.



code cleanup profiles



As can be seen from the above screen shot Full Cleanup profile has some settings set like




  • Arrange ‘this’ qualifier


  • Remove code redundancies


  • use Auto-property, if possible



and many more options set up for us by default. Similarly Reformat code profile also has some predefined settings. If we are not happy with the default profile settings we can create our own profile by clicking on Edit Profile button on the bottom left hand corner. We cannot edit the settings for the two default profiles but we can create a new profile. This gives a much finer control over what settings we want to set for cleanup operation as shown below



cleanup new profile



We can set whatever options we want for each of the available settings and save the profile. Final thing which remains is to execute the cleanup action using a particular profile and your code gets reformatted as per the chosen settings.



 



Clean Code



After cleaning up the code my final output looks like



namespace CleanCodeUsingStyleCop
{
    using System;

    public class ClassWithWarningsRemoved
    {
        public ClassWithWarningsRemoved() { }

        public ClassWithWarningsRemoved(string input)
        {
            Console.WriteLine(input);
        }

        public string Name { get; set; }

        private void DummyMethod()
        {
            Console.WriteLine("This method does nothing");
        }
    }
}


The feature of code cleanup can be applied at either an individual file level or project level or even solution level. I haven’t tried the solution level option. Incase it doesn’t work at solution level please ignore it, but it certainly works at file and project levels :).





Conclusion



Resharper is helping me and my team a lot in refactoring the code. Some of the suggestions provided by Resharper are really helpful. I am not a really big fan of using mouse while developing. Resharper just enhances that experience to a great extent. I can do so much just using the keyboard that only in extreme cases do I need to use the mouse while working with Resharper.



The combination of Resharper and StyleCop is an icing on the cake because we use the code analysis features of both StyleCop as well as FxCop in our integrated build server which is running automated builds using Cruise Control.Net (CCNET). The warnings that we would find in the integrated build can be found right inside the Visual Studio IDE and can be fixed inplace using the technique mentioned in this post.



As usual I have uploaded the complete source code to dropbox and can be downloaded as CleanCodeUsingStyleCop.zip



until next time Happy Programming :)

Share:
spacer

2 comments:

  1. Very true. The use of StyleCop make complete sence when you integrate it with Resharper. The R# plugin of StyleCop will allow you to be compliant with most of the rules simply by using the Cleanup code function CTRL+E, CTRL+C.

    Also, you may look at StyleCop add-ins to add even more rules to be checked. When you look are creating clean code in the sense of the "Clean Code" book written by Robert C. Martin, you may want to look at this: http://code.google.com/p/cleancodersstylecoprules/

    It will add a little over 20 rules than will make you code even cleaner.

    ReplyDelete
    Replies
    1. Thanks for the link. I'll have a look at it.

      Delete