User Tools

Site Tools


refactorings:extract_method

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

Reasons For Applying This Refactoring

  • Readability and Reduced Complexity
    • MIMC: Applying this refactoring reduces the code in the original method.
    • KISS: The resulting methods are typically shorter and simpler than the original one.
    • HC, SRP: The resulting methods are typically more cohesive.
  • Flexibilty, Reuse, and Robustness
    • DRY: The extracted method can be reused in other places eliminating code duplication.
    • GP, ECV: The extracted method typically has parameters so it can be invoked with different parameter values, too. This makes the method more generally applicable. Furthermore the extracted method may change separately.
  • Other Reasons
    • LMU: The extracted method carries an identifier.

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

Discussion

Discuss this wiki article and the refactoring on the corresponding talk page.

refactorings/extract_method.txt · Last modified: 2013-10-06 13:35 by christian