Refactoring
| Extract method | |
| Rename safely | |
| Spot duplication | |
| Retest after |
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.
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; }
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.
function fetchUserById(int $id): array { return dbFindUser($id); } function dbFindUser(int $id): array { return ["id" => $id, "name" => "Ada"]; }
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.
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; }
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.
$result = priceWithTax(100.0); if ($result !== 120.0) { echo "FAIL got " . $result . "\n"; exit(1); } echo "OK\n";
Next: PSR-12 style
Article author: Arthur Isaev