NetTuts.com is back with the latest part of their "Refactoring Legacy Code" series for PHP. In this latest article (part 10) they work on pulling apart longer methods into smaller, more manageable chunks.
In the sixth part of our series we talked about attacking long methods by leveraging on pair programming and viewing code from different levels. We continuously zoomed in and out, and observed both small things like naming as well as form and indentation. Today, we will take another approach: We will assume we are alone, no colleague or pair to help us. We will use a technique called "Extract till you drop" that breaks code in very small pieces. We will make all the efforts we can to make these pieces as easy to understand as possible so the future us, or any other programmer will be able to easily understand them.
This "extract 'till you drop" mentality (from Robert Martin) has you look at a piece of code and find the logic and lines that can be split out and isolated without removing functionality and interaction. They include some random code from a Stack Overflow post (checking if a number is a prime) and show how to split it out, making the logic and structure less complex and more understandable. They start with a unit test to ensure the result is the same post-refactor and fixing a few bugs along the way. They split it out into two different methods and move it from a more linear approach to something recursive.