Refactoring Legacy Code  Part 10: Dissecting Long Methods with Extractions
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.
Extract Till You Drop
I first heard about this concept from Robert C. Martin. He presented the idea in one of his videos as a simple way to refactor code that is hard to understand.
The basic idea is to take small, understandable pieces of code and extract them. It doesn't matter if you identify four lines or four characters that can be extracted. When you identify something that can be encapsulated in a clearer concept, you extract. You continue this process both on the original method and on the newly extracted pieces until you can find no piece of code that can be encapsulated as a concept.
This technique is particularly useful when you are working alone. It forces you to think about both small and larger chunks of code. It has another nice effect: It makes you think about the code  a lot! Besides the extract method or variable refactoring mentioned above, you will find yourself renaming variables, functions, classes, and more.
Let's see an example on some random code from the Internet. Stackoverflow is a good place to find small pieces of code. Here is one that determines if a number is prime:
1 
//Check if a number is prime

2 
function isPrime($num, $pf = null) 
3 
{

4 
if(!is_array($pf)) 
5 
{

6 
for($i=2;$i<intval(sqrt($num));$i++) { 
7 
if($num % $i==0) { 
8 
return false; 
9 
}

10 
}

11 
return true; 
12 
} else { 
13 
$pfCount = count($pf); 
14 
for($i=0;$i<$pfCount;$i++) { 
15 
if($num % $pf[$i] == 0) { 
16 
return false; 
17 
}

18 
}

19 
return true; 
20 
}

21 
}

At this point, I have no idea how this code works. I just found it on the Internet while writing this article, and I will discover it along with you. The process that follows may not be the cleanest. Instead, it will reflect my reasoning and refactoring as it happens, without upfront planning.
Refactoring the Prime Number Checker
According to Wikipedia:
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
As you can see this is a simple method for a simple mathematical problem. It returns true
or false
, so it should also be easy to test.
1 
class IsPrimeTest extends PHPUnit_Framework_TestCase { 
2 

3 
function testItCanRecognizePrimeNumbers() { 
4 
$this>assertTrue(isPrime(1)); 
5 
}

6 

7 
}

8 

9 
// Check if a number is prime

10 
function isPrime($num, $pf = null) 
11 
{

12 
// ... the content of the method as seen above

13 
}

When we are just playing with example code, the easiest way to go is to put everything in a test file. This way we don't have to think about what files to create, in what directories they belong, or how to include them in the other. This is just a simple example to use in order to familiarize ourselves with the technique before we apply it on one of the trivia game methods. So, all goes in a test file, you can name as you wish. I've chosen IsPrimeTest.php
.
This test passes. My next instinct is to add a few more prime numbers and than write another test with not prime numbers.
1 
function testItCanRecognizePrimeNumbers() { 
2 
$this>assertTrue(isPrime(1)); 
3 
$this>assertTrue(isPrime(2)); 
4 
$this>assertTrue(isPrime(3)); 
5 
$this>assertTrue(isPrime(5)); 
6 
$this>assertTrue(isPrime(7)); 
7 
$this>assertTrue(isPrime(11)); 
8 
}

That passes. But what about this?
1 
function testItCanRecognizeNonPrimes() { 
2 
$this>assertFalse(isPrime(6)); 
3 
}

This fails unexpectedly: 6 is not a prime number. I was expecting the method to return false
. I do not know how the method works, or the purpose of the $pf
parameter  I was simply expecting it to return false
based on its name and description. I have no idea why it is not working nor how to fix it.
This is quite a confusing dilemma. What should we do? The best answer is to write tests that pass for a decent volume of numbers. We may need to try and guess, but at least we will have some idea about what the method does. Then we can start refactoring it.
1 
function testFirst20NaturalNumbers() { 
2 
for ($i=1;$i<20;$i++) { 
3 
echo $i . '  ' . (isPrime($i) ? 'true' : 'false') . "\n"; 
4 
}

5 
}

That outputs something interesting:
1 
1  true

2 
2  true

3 
3  true

4 
4  true

5 
5  true

6 
6  true

7 
7  true

8 
8  true

9 
9  true

10 
10  false

11 
11  true

12 
12  false

13 
13  true

14 
14  false

15 
15  true

16 
16  false

17 
17  true

18 
18  false

19 
19  true

A pattern starts to emerge here. All true up to 9, then alternating up to 19. But is this pattern repeating? Try to run it for 100 numbers and you will immediately see that it is not. It is actually seems to be working for numbers between 40 and 99. It misfires once between 3039 by nominating 35 as prime. Same is true in the 2029 range. 25 is considered prime.
This exercise that started as a simple code to demonstrate a technique proves to be much more difficult than expected. I decided though to keep it because it reflects real life in a typical way.
How many times did you start working on a task that looked easy just to discover that it is extremely difficult?
We don't want to fix the code. Whatever the method does, it should continue doing it. We want to refactor it to make others understand it better.
As it does not tell prime numbers in a correct way, we will use the same Golden Master approach we learned in Lesson One.
1 
function testGenerateGoldenMaster() { 
2 
for ($i=1;$i<10000;$i++) { 
3 
file_put_contents(__DIR__ . '/IsPrimeGoldenMaster.txt', $i . '  ' . (isPrime($i) ? 'true' : 'false') . "\n", FILE_APPEND); 
4 
}

5 
}

Run this once to generate the Golden Master. It should run fast. If you need to rerun it, don't forget to delete the file before you execute the test. Otherwise the output will be attached to the previous content.
1 
function testMatchesGoldenMaster() { 
2 
$goldenMaster = file(__DIR__ . '/IsPrimeGoldenMaster.txt'); 
3 
for ($i=1;$i<10000;$i++) { 
4 
$actualResult = $i . '  ' . (isPrime($i) ? 'true' : 'false'). "\n"; 
5 
$this>assertTrue(in_array($actualResult, $goldenMaster), 'The value ' . $actualResult . ' is not in the golden master.'); 
6 
}

7 
}

Now write the test for the golden master. This solution may not be the fastest, but it is easy to understand and it will tell us exactly what number does not match if break something. But there is a little duplication in the two test methods we could extract into a private
method.
1 
class IsPrimeTest extends PHPUnit_Framework_TestCase { 
2 

3 
function testGenerateGoldenMaster() { 
4 
$this>markTestSkipped(); 
5 
for ($i=1;$i<10000;$i++) { 
6 
file_put_contents(__DIR__ . '/IsPrimeGoldenMaster.txt', $this>getPrimeResultAsString($i), FILE_APPEND); 
7 
}

8 
}

9 

10 
function testMatchesGoldenMaster() { 
11 
$goldenMaster = file(__DIR__ . '/IsPrimeGoldenMaster.txt'); 
12 
for ($i=1;$i<10000;$i++) { 
13 
$actualResult = $this>getPrimeResultAsString($i); 
14 
$this>assertTrue(in_array($actualResult, $goldenMaster), 'The value ' . $actualResult . ' is not in the golden master.'); 
15 
}

16 
}

17 

18 
private function getPrimeResultAsString($i) { 
19 
return $i . '  ' . (isPrime($i) ? 'true' : 'false') . "\n"; 
20 
}

21 
}

Now we can move un to our production code. The test runs in about two seconds on my computer, so it is manageable.
Extracting All We Can
First we can extract an isDivisible()
method in the first part of the code.
1 
if(!is_array($pf)) 
2 
{

3 
for($i=2;$i<intval(sqrt($num));$i++) { 
4 
if(isDivisible($num, $i)) { 
5 
return false; 
6 
}

7 
}

8 
return true; 
9 
}

That will enable us to reuse the code in the second part like this:
1 
} else { 
2 
$pfCount = count($pf); 
3 
for($i=0;$i<$pfCount;$i++) { 
4 
if(isDivisible($num, $pf[$i])) { 
5 
return false; 
6 
}

7 
}

8 
return true; 
9 
}

And as soon as we started to work with this code we observed that it is carelessly aligned. Braces are sometimes at the begining of the line, other times at the end.
Sometimes, tabs are used for indentation, sometimes spaces. Sometimes there are spaces between operand and operator, sometimes not. And no, this is not specially created code. This is real life. Real code, not some artificial exercise.
1 
//Check if a number is prime

2 
function isPrime($num, $pf = null) { 
3 
if (!is_array($pf)) { 
4 
for ($i = 2; $i < intval(sqrt($num)); $i++) { 
5 
if (isDivisible($num, $i)) { 
6 
return false; 
7 
}

8 
}

9 
return true; 
10 
} else { 
11 
$pfCount = count($pf); 
12 
for ($i = 0; $i < $pfCount; $i++) { 
13 
if (isDivisible($num, $pf[$i])) { 
14 
return false; 
15 
}

16 
}

17 
return true; 
18 
}

19 
}

That looks better. Immediately the two if
statements look very similar. But we can't extract them because of the return
statements. If we don't return we will break the logic.
If the extracted method would return a boolean and we compare it to decide if we should or not return from isPrime()
, that would not help at all. There may be a way to extract it by using some functional programming concepts in PHP, but maybe later. We can do something simpler first.
1 
function isPrime($num, $pf = null) { 
2 
if (!is_array($pf)) { 
3 
return checkDivisorsBetween(2, intval(sqrt($num)), $num); 
4 
} else { 
5 
$pfCount = count($pf); 
6 
for ($i = 0; $i < $pfCount; $i++) { 
7 
if (isDivisible($num, $pf[$i])) { 
8 
return false; 
9 
}

10 
}

11 
return true; 
12 
}

13 
}

14 

15 
function checkDivisorsBetween($start, $end, $num) { 
16 
for ($i = $start; $i < $end; $i++) { 
17 
if (isDivisible($num, $i)) { 
18 
return false; 
19 
}

20 
}

21 
return true; 
22 
}

Extracting the for
loop as a whole is a bit easier, but when we try to reuse our extracted method in the second part of the if
we can see that it won't work. There is this mysterious $pf
variable about which we know almost nothing.
It seems like it checks if the number is divisible by a set of specific divisors instead of taking all numbers up to the other magical value determined by intval(sqrt($num))
. Maybe we could rename $pf
into $divisors
.
1 
function isPrime($num, $divisors = null) { 
2 
if (!is_array($divisors)) { 
3 
return checkDivisorsBetween(2, intval(sqrt($num)), $num); 
4 
} else { 
5 
return checkDivisorsBetween(0, count($divisors), $num, $divisors); 
6 
}

7 
}

8 

9 
function checkDivisorsBetween($start, $end, $num, $divisors = null) { 
10 
for ($i = $start; $i < $end; $i++) { 
11 
if (isDivisible($num, $divisors ? $divisors[$i] : $i)) { 
12 
return false; 
13 
}

14 
}

15 
return true; 
16 
}

This is one way to do it. We added a forth, optional, parameter to our checking method. If it has a value, we use it, otherwise we use $i
.
Can we extract anything else? What about this piece of code: intval(sqrt($num))
?
1 
function isPrime($num, $divisors = null) { 
2 
if (!is_array($divisors)) { 
3 
return checkDivisorsBetween(2, integerRootOf($num), $num); 
4 
} else { 
5 
return checkDivisorsBetween(0, count($divisors), $num, $divisors); 
6 
}

7 
}

8 

9 
function integerRootOf($num) { 
10 
return intval(sqrt($num)); 
11 
}

Isn't that better? Somewhat. It is better if the person coming after us doesn't know what intval()
and sqrt()
are doing, but it doesn't help make the logic easier to understand. Why do we end our for
loop at that specific number? Maybe this is the question our function name should answer.
1 
[PHP]//Check if a number is prime 
2 
function isPrime($num, $divisors = null) { 
3 
if (!is_array($divisors)) { 
4 
return checkDivisorsBetween(2, highestPossibleFactor($num), $num); 
5 
} else { 
6 
return checkDivisorsBetween(0, count($divisors), $num, $divisors); 
7 
}

8 
}

9 

10 
function highestPossibleFactor($num) { 
11 
return intval(sqrt($num)); 
12 
}[PHP] 
That is better as it explains why we stop there. Maybe in the future we can invent a different formula to determine that number. The naming also introduced a little inconsistency. We called the numbers factors, which is a synonym of divisors. Maybe we should pick one and use that only. I will let you make the renaming refactoring as an exercise.
The question is, can we extract any further? Well, we must try till we drop. I mentioned the functional programming side of PHP a few paragraphs above. There are two main functional programming characteristics that we can easily apply in PHP: first class functions and recursion. Whenever I see an if
statement with a return
inside a for
loop, like in our checkDivisorsBetween()
method, I think about applying one or both techniques.
1 
function checkDivisorsBetween($start, $end, $num, $divisors = null) { 
2 
for ($i = $start; $i < $end; $i++) { 
3 
if (isDivisible($num, $divisors ? $divisors[$i] : $i)) { 
4 
return false; 
5 
}

6 
}

7 
return true; 
8 
}

But why should we go through such a complex thought process? The most annoying reason is that this method does two distinct things: It cycles and it decides. I want it only to cycle and leave the decision to another method. A method should always do a single thing and do it well.
1 
function checkDivisorsBetween($start, $end, $num, $divisors = null) { 
2 
$numberIsNotPrime = function ($num, $divisor) { 
3 
if (isDivisible($num, $divisor)) { 
4 
return false; 
5 
}

6 
};

7 
for ($i = $start; $i < $end; $i++) { 
8 
$numberIsNotPrime($num, $divisors ? $divisors[$i] : $i); 
9 
}

10 
return true; 
11 
}

Our first attempt was to extract the condition and the return statement into a variable. This is local, for the moment. But the code doesn't work. Actually the for
loop complicates things quite a bit. I have a feeling that a little recursion will help.
1 
function checkRecursiveDivisibility($current, $end, $num, $divisor) { 
2 
if($current == $end) { 
3 
return true; 
4 
}

5 
}

When we think about recursivity we must always start with the exceptional cases. Our first exception is when we reach the end of our recursion.
1 
function checkRecursiveDivisibility($current, $end, $num, $divisor) { 
2 
if($current == $end) { 
3 
return true; 
4 
}

5 

6 
if (isDivisible($num, $divisor)) { 
7 
return false; 
8 
}

9 
}

Our second exceptional case that will break the recursion is when the number is divisible. We don't want to continue. And that is about all the exceptional cases.
1 
ini_set('xdebug.max_nesting_level', 10000); 
2 
function checkDivisorsBetween($start, $end, $num, $divisors = null) { 
3 
return checkRecursiveDivisibility($start, $end, $num, $divisors); 
4 
}

5 

6 
function checkRecursiveDivisibility($current, $end, $num, $divisors) { 
7 
if($current == $end) { 
8 
return true; 
9 
}

10 

11 
if (isDivisible($num, $divisors ? $divisors[$current] : $current)) { 
12 
return false; 
13 
}

14 

15 
checkRecursiveDivisibility($current++, $end, $num, $divisors); 
16 
}

This is another attempt to use recursion for our problem, but unfortunately, recurring 10.000 times in PHP leads to a crash of PHP or PHPUnit on my system. So this seems to be another dead end. But if it would have been working, it would have been a nice replacement of the original logic.
Challenge
When I wrote the Golden Master, I intentionally overlooked something. Let's just say the tests are not covering as much code as they should. Can you spot the problem? If yes, how would you approach it?
Final Thoughts
"Extract till you drop" is a good way to dissect long methods. It forces you to think about small pieces of code and to give the pieces a purpose by extracting them into methods. I find it amazing how this simple procedure, together with frequent renaming, can help me discover that some code does things I never thought possible.
In our next and final tutorial about refactoring, we will apply this technique to the trivia game. I hope you liked this tutorial that turned out to be a little bit different. Instead of talking on textbook examples, we took some real code and we had to fight with the real problems we face every day.