Refactoring
A refactor changes the shape of PHP code without changing what it does, and every step is proved by a run. The examples below are small programs with their output, so the behaviour before and after the change is visible on the page.
Extract method
When a function scrolls past one screen, carve out one job and give it a name. The caller keeps the story line while each helper hides one detail. Small named steps are easier to test than one long recipe.
<?php function orderTotal(array $items): float { return calcSubtotal($items) + calcShipping($items); } function calcSubtotal(array $items): float { $sum = 0.0; foreach ($items as $item) { $sum += (float) $item["price"]; } return $sum; } function calcShipping(array $items): float { return count($items) * 5.0; } $items = [["price" => 10.0], ["price" => 20.0]]; echo orderTotal($items), PHP_EOL;
php extract.php
40
The caller reads as one sentence, and the two parts are separate helpers that can be tested alone: 30 for the items and 10 for the shipping of two of them.
Rename safely
A vague name like handle or process hides bugs because every caller guesses its meaning. Rename one symbol at a time with the editor rename command, then run the checks before touching the next name.
<?php function fetchUserById(int $id): array { return dbFindUser($id); } function dbFindUser(int $id): array { return ["id" => $id, "name" => "Ada"]; } $user = fetchUserById(7); echo $user["id"], " ", $user["name"], PHP_EOL;
php rename.php
7 Ada
Both names say what they do now, and the call still returns the same row after the rename, which is the proof that the step changed no behaviour.
Spot duplication
Pasted blocks drift apart: one copy learns the new tax rate while the other keeps the old one. Pull the shared math into one function so the rule lives in a single place. More copy hunting tricks are in Deduplication in PHP.
<?php function priceWithTax(float $price): float { return $price + $price * 0.2; } function cartWithTax(array $prices): float { $sum = 0.0; foreach ($prices as $price) { $sum += priceWithTax((float) $price); } return $sum; } echo priceWithTax(100.0), PHP_EOL; echo cartWithTax([100.0, 50.0]), PHP_EOL;
php dedup.php
120
180
One price and the whole cart agree, because both go through the same function. Changing the rate in one place changes all three numbers of the next run.
Retest after
Every refactor ends with proof: run the checks and compare one output before and after the change. If behavior matches and the structure is simpler, keep the change. If anything wobbles, revert and slice the step smaller.
<?php function priceWithTax(float $price): float { return $price + $price * 0.2; } $result = priceWithTax(100.0); if ($result !== 120.0) { echo "FAIL got " . $result . "\n"; exit(1); } echo "OK\n";
php check.php
OK
The comparison is the same value the previous section printed, so the check would have caught a change to the rule. A stricter form compares one decimal place, which this float happens to match exactly.
Exercises
- Give the shipping function a base fee and run the extract example again.
- Rename dbFindUser to findUserRow and update its one caller.
- Add a third price to the cart and predict the two output lines before the run.
- Change the tax rate to 0.1 and describe which check fails first.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does an extract method refactor change?
Answer
The shape of the code, not its behaviour
One long step becomes named steps, and the same inputs still give the same result.
-
Why rename one symbol at a time and run the checks in between?
Answer
Each rename is a separate small change whose breakage is easy to spot
A failure right after one rename points at one name instead of a whole batch.
-
What is the cost of two copies of a business rule?
Answer
They drift apart, so one copy keeps an old rate
Two places to edit means one of them is missed sooner or later, and the outputs disagree.
-
What proves that a refactor kept the behaviour?
Answer
The same input gives the same output as before
A comparison against a known result is the only evidence that nothing changed for the reader.
-
What does this program print?
<?php function priceWithTax(float $price): float { return $price + $price * 0.2; } echo priceWithTax(50.0);Answer
60
A fifth of fifty is ten, so the price with tax is sixty.
-
What does this program print?
<?php function subtotal(array $rows): float { $sum = 0.0; foreach ($rows as $row) { $sum += (float) $row["price"]; } return $sum; } function shipping(array $rows): float { return count($rows) * 5.0; } $rows = [["price" => 10.0], ["price" => 20.0]]; echo subtotal($rows) + shipping($rows);Answer
40
The items cost thirty and the two rows add ten of shipping.
-
What does this program print?
<?php function tax(float $price): float { return $price * 0.2; } echo tax(100.0), " ", tax(50.0);Answer
20 10
The function returns the tax alone, which is twenty and ten for the two prices.
-
What does this program print?
<?php function total(array $prices): float { $sum = 0.0; foreach ($prices as $price) { $sum += (float) $price; } return $sum; } $result = total([10.0, 20.0]); if ($result !== 30.0) { echo "FAIL"; exit(1); } echo "OK";Answer
OK
The sum is exactly thirty for these float values, so the guard passes and the last line runs.
-
A refactor makes a big rename and a logic change in one step, and a check fails. What is the problem?
Answer
Two changes hide which of them broke the result
One step at a time keeps the failure attributable, which is the whole point of the small steps.
-
Why is a duplicated
price * 0.2harder to keep right than a function call?Answer
Every copy must be found and changed when the rate changes
The rule lives in every copy, and a search for the number misses the copy written another way.
The examples call count() and exit(). The programs on this page were run with PHP 8.5.13 (php -v) with the commands shown above.
Article author: Arthur Isaev