Refactoring 010 - Extract Method Object

Refactoring 010 - Extract Method Object

You have a big algorithmic method. Let's break it.

Maxi Contieri
·Nov 7, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems Addressed
  • Related Code Smells
  • Steps
  • Sample Code
  • Type
  • Safety
  • Why code is better?
  • Tags
  • Related Refactorings
  • See also
  • Conclusion
  • Credits

TL;DR: Long methods are bad. Move them and break them.

Problems Addressed

Related Code Smells

Steps

  1. Create an object to represent an invocation of the method

  2. Move the big method to the new object

  3. Convert the temporary variables of the method into private attributes.

  4. Break the big method in the new object by using Extract Method

  5. Remove parameters from method invocation by also converting them to private attributes

Sample Code

Before

class BlockchainAccount {
  // ...
  public double balance() {
    string address;    
    // Very long untestable method
  }
}

After

class BlockchainAccount {
  // ...
  public double balance() {
    return new BalanceCalculator(this).netValue();
  }
}

// 1. Create an object to represent an invocation of the method
// 2. Move the big method to the new object
// 3. Convert the temporary variables of the method into private attributes.
// 4. Break the big method in the new object by using the Extract Method
// 5. Remove parameters from method invocation by also converting them to private attributes 


class BalanceCalculator {
  private string address;
  private BlockchainAccount account;

  public BalanceCalculator(BlockchainAccount account) {
    this.account = account;
  }

  public double netValue() {
    this.findStartingBlock();
    //...
    this computeTransactions();
  }
}

Type

[X] Semi-Automatic

Some IDEs have tools to extract a function into a method object.

Safety

This is a syntactic and structural refactoring.

We can make the changes automatically in a safe way.

Why code is better?

We extract the logic into a new component.

We can unit-test it, reuse it, exchange it, etc.

Tags

  • Bloaters

Related Refactorings

See also

Wikipedia: Strategy Pattern

Method Object Definition

Refactoring.guru

C2 Wiki

Conclusion

The Method-Object is suitable when we are using several extract methods passing partial state among them as parts of an algorithm.

We store these partial computations in the method-object internal state.

A strong indicator of method object opportunity is when computations are not cohesively related to the host method.

We can also reify anonymous functions with more atomic, cohesive, and testable method objects.

Credits

Image by Manuel de la Fuente on Pixabay


This article is part of the Refactoring Series.

 
Share this