You have a big algorithmic method. Let's break it.
TL;DR: Long methods are bad. Move them and break them.
Problems Addressed
Lack of Testability
Accidental Complexity
Related Code Smells
Code Smell 10 - Too Many Arguments
Maxi Contieri ・ Oct 29 '20
Code Smell 21 - Anonymous Functions Abusers
Maxi Contieri ・ Nov 10 '20
Code Smell 36 - Switch/case/elseif/else/if statements
Maxi Contieri ・ Nov 28 '20
Code Smell 149 - Optional Chaining
Maxi Contieri ・ Jul 16 '22
Steps
Create an object to represent an invocation of the method
Move the big method to the new object
Convert the temporary variables of the method into private attributes.
Break the big method in the new object by using Extract Method
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
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.