I do a lot of work with IntelliJ these days and wanted to see if my favourite toolchain (Visual Studio + Resharper) provide a better experience for extracting classes. Here are my learnings.
I have a simple class with too many responsibilities. Easily to see via the "And" in the method name (Nitriq had this as a code rule since the beginning http://www.nitriq.com/).
Lets say I want to split up this class in a "Mapper" and a "XmlGenerator".
How would you do this?
How would you do this in an automated way?
Figure: The smelly class "XmlGenerator" with too many responsibilities
C# and Resharper come first.
Figure: Resharper to the rescue -> "Extract class"
When you click on "Select all suggested members" Resharper tries to find methods that belong together. We would call this Cohesion.
Resharper is not sooo smart to understand responsibilities. It checks who calls who and selects methods that have a call dependency. In our case that would be all methods :/
--> Maybe AI will solve this? 😊
Figure: The human brain decided about cohesion here
Lets go ahead and apply this refactoring.
Resharper does a good job to refactor this. The only ugliness remains is that the call site to the "map" methods use now the dependency in the XmlGenerator and not the Mapper itself.
Figure: Mapper dependency exposed to the outside world
Lets fix that! I give you only hints so that you can try for yourself.
- Inline the field.
- Inline the property
- "Extract field" new Mapper + initialize from constructor
- Introduce Parameter in constructor
- Rename classes
- Happy days
Figure: Nice code that separates XML generation from mapping of data.
The code to try this yourself is on github https://github.com/peitor/Refactorings-ExtractClass/
No comments:
Post a Comment