refactorings:extract_method
Table of Contents
Extract Method
Alternative Names
Context
Purpose
Extract a portion of code from a (probably long) method into a new one in order to improve cohesion and readability of the source.
Description
Mechanics
TODO: explain mechanics
This refactoring is often automated by modern IDEs.
Origin
Martin Fowler: Refactoring: Improving the Design of Existing Software
Reasons For Applying This Refactoring
Reasons Against Applying This Refactoring
- MIMC: Applying this refactoring adds another (private) method and another method call.
- MIMC, LC: If the extracted method has very many parameters (see long parameter list), it has a high coupling to the calling method. In such a case it is either the wrong piece of code which is extracted or the parameter list should be shortened by applying further refactorings.
- MP: If you cannot find a suitable name for the new method, it it probably the wrong piece of code to extract.
- PSU: Technically it is possible to extract almost arbitrary portions of code into a new method. But extracting the wrong piece of code results in a PSU violation. Either the extracted method is not understandable on its own, i.e. you have to read the calling method in order to understand the extracted one. Or the calling method is not understandable anymore without reading the extracted method. A typical problem here is that the extracted method takes parameters where it's not clear why they are needed without reading the code of the extracted method. In either case the refactoring didn't improve the code. Rather you still have to read both methods so there are no readability and simplicity benefits. Moreover the code which has to be read together is now separated so reading both methods may involve jumping back and forth in different parts of the source. In such a case extracting the method is a bad thing.
Patterns the Refactoring May Lead to
Examples
Description Status
Further Reading
Martin Fowler: Refactoring: Improving the Design of Existing Software
- Reafctoring.com: Extract Method
Discussion
Discuss this wiki article and the refactoring on the corresponding talk page.
refactorings/extract_method.txt · Last modified: 2021-10-18 22:22 by christian