Refactoring C# Code With ReSharper Help


A pattern that I do quite often is to first right out code that actually works, then when I see a pattern repeat itself, I like to refactor that code to try and avoid the repetitive code.  Reasons include:

  • Smaller Code
  • Less Chance For Error
  • Don’t Repeat Yourself (DRY)

As an example, the c# code I’m working on now involves reading key values to be used with the Stripe payment service.  Here is the code I first wrote:

The first thing I do is to look for the pattern and try and pull out variables that I know are going to be helpful in refacotring. You can see below that I pulled out the keyAppName variable and I also changed the assignment to be to a new variable rather than to the exact target I wanted (keyValue instead of view.StripePublicAndPrivateKeys.StripeSecretKey). The reason is my plan is to pull out the common functionality and to do this I don’t want to have to pass into a common method lot’s of extranious classes.

Next, through the helpfulness of JetBrain’s ReSharper, I select the code I want to refactor and then right mouse button, say "Extract Method" and this is what I get:


The method that is created is this:


Which, when shown, changes the code to the following (notice that the method GetKeyValueFromStrip is created.

And, that can be simplified to simply

And now, all 4 keys (public and private for both live and test) can be generated quite simply and with little chance of typos as follows

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he’s a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Get every new post delivered to your Inbox

Join other followers: