For a few years now my most common refactoring was Extract Method. Got a big method? Extract sub methods. Got a deeply nested method? Extract each level into a new method. Got any other problem? You should probably look for methods to extract.
I've change my mind; these days I'm all about Extract Class, or more accurately Replace Method With Class. Got a big method? Cut out it's body and paste it into a new method on a new class. Got a deeply nested method? Well... I guess Extract Method still works better for that one. Got any other problem though? Just pick the largest method (or #region for you C# folks) and extract it to a new class.
Why the sudden change of mind? Recent real world experience that is best explained with bulleted lists within a matrix:
Extract Method | Extract Class | |
---|---|---|
Mess | Unless there's a lot of duplication that you can quickly remove, the class size stays about the same. | Immediately reduces the class size by moving code to a new class. The compiler will tell you what it depends on and what depends on it. |
Power | You get a new method:
| You get a new class:
|
Concepts | Small, local, procedural:
| Large, project-wide, object oriented:
|
or, in prose form: Extract Class immediately reduces the amount of code you have to worry about, improves cohesiveness of the remaining class, and gives you familiar object oriented techniques to work with.
Of course it's good to see if related methods could be extracted into a new class after extracting a method and it's probably good to break up the monster method after hiding it in a new class. I just found it much easier to make progress when I relied on extracting large methods to new classes first.
No comments:
Post a Comment