Do you follow the SOLID principles, and use Resharper? Did you know that Resharper can help you refactor for SOLID principles? Well today, I’m going to show you how you can use Resharper to refactor for the Single Responsibility rule!
As a developer at Springthrough I have become passionate about Single Responsibility (the ‘S’ in SOLID). Single Responsibility pattern allows us to write our code in small chunks. The benefit of this in the long-term is that when a bug is found or changes are requested, we have less code to work with reducing our development time and risk. If you adhere to this pattern you will find that maintenance is quicker and easier, and your project architecture is easier to manage and understand.
Recently, I had to write a class to do something on a deadline. After finishing the class, I couldn’t help but notice that I had violated the Single Responsibility Rule.
Here’s a class outline:
Notice that there are two things going on here. Getting Invoices and Processing Invoices. There’s a third item as well, translating. But that’s a static method so we won’t count that.
Stick the cursor at the top of the class, in the class name. Then use Resharper to Extract a class:
My Current class is a Processor and I think my second class should be a Finder. I’ll call my extracted class a Finder. When I start to select which methods that I want to move to my extracted class, Resharper will warn me about dependent methods that will break my build if I don’t grab them.
All I need to do is “Fix the Hate” and select all of my “Find” methods to isolate my “Find” responsibility. Then everything is happy:
Resharper will automatically add a field at the top of my class for my new extracted class:
And it updates ALL of my usages for those methods to the new extracted class.
So this:
Changes to this:
What a nice class outline:
And the processor looks a lot cleaner:
I now have two single Responsibilities. Now one class is only concerned with finding invoices and the other class is only concerned with processing invoices. All I really have to do now is refactor a bit for Inversion of Control. I’ll do that using Resharper’s Extract Interface, then I’ll create a new constructor, and then pass in a concrete of my new interface.
Put your cursor at the top of the Finder class and you can extract interface from the Resharper menu:
Create your interface:
Then I’ll change this:
To this:
and Initialize it from a new Constructor:
And boom! I refactored for both Single Responsibility and the Dependency Inversion Principles.
Fixing usages is easy:
Now, all I need to do is implement Dependency Injection!
In the efforts of keeping client projects maintainable and easy to develop, the SOLID principals are immensely beneficial. It will save development hours and allow for better code quality. In an effort to share our knowledge we’ve gained, we hope this article can help you become a more efficient developer and partner to your clients!