Working with big methods is always hard. Usually big methods are breaking most of the design principles. But most importantly it’s an indication that the method is breaking single responsibility because that method is trying to do so much.
I learned this new technique from Working Effectively With Legacy Code by Michael C. Feathers. I found it very interesting way to break big methods.
It’s very hard to pull such methods under test harness. The main focus area for such methods is to make it testable.
Sometimes there is a code in big method which is secondary to the method’s main purpose.
What’s in the name
Dictionary meaning of glean means: extract from various sources. Collect gradually and bit by bit. Wiki says: Gleaning is the act of collecting leftover crops from farmers’ fields after they have been commercially harvested or on fields where it is not economically profitable to harvest.
- You divide your big method into two parts – core behavior and one that’s not core. An example of this would be separating sendMail() functionality while saving your addPayment() method.
- You write the tests for the main logic.
- You extract things that is not covered under the tests
- There is a confidence that you are preserving the important behavior
- It feels like a cop-out. You are preserving one set of behavior and working with another unprotected
- This method is really powerful when the core behavior in entangled with other behavior
These steps are as per my understanding. There maybe different ways.
- Have a overview of the method. Keep a watch on what’s the most touched variable.
- The most touched variable would probably give you an idea of what’s the main behavior.
- See if you can group the main behavior together.
- Put temporary comments in the method to indicate what behavior the code is trying to do. This would be the base for extracting your methods. The comments would help you to name the extracted method.
- If you have the test harness, write the test case for the main behavior. Ignore the tests for other behaviors for now.
- Once you have grouped 2-3 behaviors, you can do “Extract method refactoring” and pull the code out into its own method. Most IDEs have this refactoring technique. I will link it here once I have a post for it.
- Again repeat the steps to find other behaviors and keep in extracting them in the same way.
- You are done. If time permits you can write tests for remaining un-important but required behaviors.