Resharper VS IntelliJ -> Extract Class

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.

  1. Inline the field.
  2. Inline the property
  3. "Extract field" new Mapper + initialize from constructor
  4. Introduce Parameter in constructor
  5. Rename classes
  6. Happy days

Result:

Figure: Nice code that separates XML generation from mapping of data.


Now lets try this in IntelliJ

We have the same starting point: The tests uses 2 public methods from the XmlGenerator


In IntelliJ the refactoring is called "Extract delegate" and not "Extract class"


IntelliJ inroduces a "Man in the middle smell" which is easy to fix by "Inline" or call site rewrite.

Interesting though that the 2 tools behave so different and have a different name for the refactoring.

IntelliJ seems to be a bit more sophisticated with "Extract Class" refactorings. It seems to provide 3 options as per the documentation https://www.jetbrains.com/help/idea/extract-into-class-refactorings.html 
The Resharper documentation can be found here https://www.jetbrains.com/help/resharper/Refactorings__Extract_Class.html 


The code to try this yourself is on github https://github.com/peitor/Refactorings-ExtractClass/ 

No comments:

Post a Comment

Latest Posts

Popular Posts