Skip to content

Lesson 44 of 45 · Testing as a Discipline

Refactoring as a Discipline

Intermediate•
lesson•
November 7, 2026•
~10 min read

"We're refactoring" usually isn't refactoring

You've heard this in standups: "I'm refactoring the billing module." Later: "Still refactoring." Later still: "Almost done with the refactor." When the work lands, you read the diff and see new features, deleted features, schema changes, behavior changes, and a thousand small style edits. That is a rewrite with a refactoring label on it.

In the codebases I've worked on, many "refactoring" PRs are rewrites with bonus changes mixed in. They're hard to review and risky to ship. This lesson covers what refactoring is in the original Fowler sense, what it requires, and how the rest of the course makes it possible. The capstone that follows applies it to a larger example.

What refactoring actually means

Martin Fowler's definition, as stated on refactoring.com (his book Refactoring came out in 1999, with a second edition in 2018):

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.

The key phrase is without changing its external behavior. Anything a caller could notice is off limits: adding or removing features, and fixing bugs, because a bug fix changes what the code does. Renaming, extracting, inlining, moving code between classes, and replacing a conditional with polymorphism are all allowed, because the goal is the internal structure.

If you spot a bug while refactoring, note it, finish the refactoring, and fix the bug as separate work.

The two hats

Fowler's Refactoring describes the work as wearing one of two hats, never both:

  • The refactoring hat. You're improving structure. You change nothing about behavior. You commit small, safe transformations, and the tests stay green throughout.

  • The feature hat. You're adding behavior. The tests for the new behavior may fail until you finish.

A refactoring PR with feature changes mixed in is risky: you can't tell which change broke what, and reviewers can't separate "did the refactoring preserve behavior?" from "did the feature get implemented correctly?". If a PR mixes the two, the fix is to split it into a refactoring commit and a feature commit.

In practice you switch hats on purpose: refactor the area you're about to change, commit, add the feature, commit, then clean up what you just wrote.

Three named refactorings

The catalog lists dozens of named refactorings. This lesson uses the 2018 edition's names, as the online catalog does, and gives the first edition's name where it differs. Three are enough for the worked example:

  • Extract Function (Extract Method in the first edition). Take a chunk of code and turn it into its own function with a name.

  • Replace Conditional with Polymorphism. A match or if over a type code becomes a Strategy or a polymorphic call.

  • Change Function Declaration (Rename Method in the first edition). Change a name to express intent better.

A worked sequence

Each step below is small enough to be its own commit.

The starting point is a legacy cancel() method that computes a refund inline, branching on a policy string with a nested date check for one of the branches. It works on LegacyReservation, a stand-in for an old class that keeps its policy as a string, unlike the Reservation from earlier lessons. It has its own refund rules: a strict reservation refunds in full at 5 or more days before check-in, half at 1 or more, and nothing otherwise. Those rules differ from the StrictCancellation in Lesson 19 of this course, and this lesson keeps the legacy rules as they are. Any policy string other than 'flexible' or 'strict' falls through to a full refund.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class LegacyReservation { private ?CarbonImmutable $cancelledAt = null; public function __construct( private readonly string $policy, private readonly Money $totalPaid, public readonly DateRange $stayDates, ) {} public function policy(): string { return $this->policy; } public function totalPaid(): Money { return $this->totalPaid; } public function markCancelled(CarbonImmutable $cancelledAt): void { $this->cancelledAt = $cancelledAt; } public function cancelledAt(): ?CarbonImmutable { return $this->cancelledAt; } }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class ReservationCancellationService { public function cancel(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { $refund = $reservation->totalPaid(); if ($reservation->policy() === 'flexible') { $refund = $reservation->totalPaid(); } elseif ($reservation->policy() === 'strict') { $daysBeforeCheckIn = (int) $cancelledAt->diffInDays($reservation->stayDates->checkIn, false); if ($daysBeforeCheckIn >= 5) { $refund = $reservation->totalPaid(); } elseif ($daysBeforeCheckIn >= 1) { $refund = $reservation->totalPaid()->percentage(50); } else { $refund = Money::zero($reservation->totalPaid()->currency); } } $reservation->markCancelled($cancelledAt); return $refund; } }

Before touching it, pin what it does. A characterization test records the current behavior, including the unknown-policy fall-through, whether or not anyone would design it that way today:

PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Billing\Currency; use App\Billing\Money; use App\Reservations\DateRange; use App\Reservations\LegacyReservation; use App\Reservations\ReservationCancellationService; use Carbon\CarbonImmutable; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class ReservationCancellationServiceTest extends TestCase { #[DataProvider('refundTiers')] public function test_refund_matches_the_legacy_rules(string $policy, string $cancelledOn, int $expectedCents): void { // Given $reservation = new LegacyReservation( policy: $policy, totalPaid: Money::fromCents(42000, Currency::usd()), stayDates: DateRange::ofNights(CarbonImmutable::parse('2026-06-10'), 3), ); $cancelledAt = CarbonImmutable::parse($cancelledOn); // When $refund = $this->service()->cancel($reservation, $cancelledAt); // Then $this->assertSame($expectedCents, $refund->amountInCents); $this->assertEquals($cancelledAt, $reservation->cancelledAt()); } /** * @return iterable<string, array{string, string, int}> */ public static function refundTiers(): iterable { yield 'flexible, on check-in day' => ['flexible', '2026-06-10', 42000]; yield 'strict, 5 days out' => ['strict', '2026-06-05', 42000]; yield 'strict, 4 days out' => ['strict', '2026-06-06', 21000]; yield 'strict, 1 day out' => ['strict', '2026-06-09', 21000]; yield 'strict, on check-in day' => ['strict', '2026-06-10', 0]; yield 'unknown policy falls through to a full refund' => ['no_such_policy', '2026-06-10', 42000]; } private function service(): ReservationCancellationService { return new ReservationCancellationService(); } }

The test builds the service in one place, service(), so the steps below touch only that line.

Step 1: Extract Function. The refund calculation is one job, cancelling the reservation is another. Pull the calculation into its own method, refundFor(). Nothing about what the method returns changes, only where the code lives. The extraction also flattens the branches into early returns, and the characterization test still pins the behavior:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class ReservationCancellationService { public function cancel(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { $refund = $this->refundFor($reservation, $cancelledAt); $reservation->markCancelled($cancelledAt); return $refund; } private function refundFor(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { if ($reservation->policy() !== 'strict') { return $reservation->totalPaid(); } $daysBeforeCheckIn = (int) $cancelledAt->diffInDays($reservation->stayDates->checkIn, false); if ($daysBeforeCheckIn >= 5) { return $reservation->totalPaid(); } if ($daysBeforeCheckIn >= 1) { return $reservation->totalPaid()->percentage(50); } return Money::zero($reservation->totalPaid()->currency); } }

Step 2: Replace Conditional with Polymorphism. The branch on policy() is a type code standing in for two different behaviors. Give each behavior its own class behind a shared interface and let the caller ask the right object instead of asking a string. This is the shape Lesson 19 of this course arrives at with its CancellationPolicy classes, but the classes below keep the legacy rules and the legacy string, so they are named RefundPolicy to stay apart from Lesson 19's.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; interface RefundPolicy { public function refundFor(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money; }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class FlexibleRefundPolicy implements RefundPolicy { public function refundFor(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { return $reservation->totalPaid(); } }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class StrictRefundPolicy implements RefundPolicy { public function refundFor(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { $daysBeforeCheckIn = (int) $cancelledAt->diffInDays($reservation->stayDates->checkIn, false); if ($daysBeforeCheckIn >= 5) { return $reservation->totalPaid(); } if ($daysBeforeCheckIn >= 1) { return $reservation->totalPaid()->percentage(50); } return Money::zero($reservation->totalPaid()->currency); } }

A small factory turns the string into the right object: StrictRefundPolicy for 'strict' and FlexibleRefundPolicy for every other value, which keeps the old fall-through to a full refund.

PHP
<?php declare(strict_types=1); namespace App\Reservations; final class RefundPolicyFactory { public function for(string $policy): RefundPolicy { return match ($policy) { 'strict' => new StrictRefundPolicy(), default => new FlexibleRefundPolicy(), }; } }

The service's private refundFor() goes away. cancel() asks the factory for the policy and calls it:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class ReservationCancellationService { public function __construct(private RefundPolicyFactory $policies) {} public function cancel(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { $refund = $this->policies->for($reservation->policy())->refundFor($reservation, $cancelledAt); $reservation->markCancelled($cancelledAt); return $refund; } }

Step 3: Change Function Declaration. The call reads "the policy for this reservation's policy, refund-for the reservation", and the For repeats what for() already says. Rename refundFor() to refund() on the interface and both implementations. The interface and the service end up like this:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; interface RefundPolicy { public function refund(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money; }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use Carbon\CarbonImmutable; final class ReservationCancellationService { public function __construct(private RefundPolicyFactory $policies) {} public function cancel(LegacyReservation $reservation, CarbonImmutable $cancelledAt): Money { $refund = $this->policies->for($reservation->policy())->refund($reservation, $cancelledAt); $reservation->markCancelled($cancelledAt); return $refund; } }

That makes three commits and three small diffs, each reviewable on its own. The characterization test stayed green through all three without a single assertion changing. The only edit was in service(), once, in step 2: the service gained a constructor argument, so the call became new ReservationCancellationService(new RefundPolicyFactory()).

That is the two-hats rule in practice: what cancel() returns for a given reservation and cancellation time never changed. A new assertion or a new case means the feature hat is on, and it belongs in a separate commit. So does bringing these legacy rules in line with Lesson 19's.

Why tests are required

The only way to know behavior didn't change is a test suite that confirms it. Refactoring without tests is gambling: you change code, cross your fingers, and hope nobody notices a regression. If the tests don't exist, write them first, as the characterization test above does, and "I was careful" is not a substitute for them.

This chapter runs in the order it does because refactoring is the payoff for the rest of it:

  • The testing pyramid and test doubles tell you where each kind of test belongs and how to isolate the code under change.

  • TDD shapes the code so it is easier to refactor in the first place.

  • BDD pins the behavior callers care about, which is the behavior a refactoring must preserve.

  • Mutation testing tells you whether the suite verifies the right things.

PHP and Laravel tooling

Use your IDE's rename, extract and move tools (PhpStorm ships all three) instead of editing by hand, and use Rector when the same change spans thousands of files. Run PHPStan in CI and your test suite plus a formatter (Pint in Laravel, PHP CS Fixer in Symfony) in a pre-commit hook, so a missed call site or a typo in a rename fails before review.

When refactoring earns its place

Refactoring earns its place when:

  • You're about to add a feature in messy code. Wear the refactoring hat first. Make the change easy, then make the easy change (Kent Beck's framing).

  • You discover a smell while reading code. The Boy Scout Rule: small cleanups, in the file you're already in, leave the campsite better.

  • You're paying down explicit debt. A planned refactoring project, with scope and review, to clean up something the team has agreed is overdue.

  • A test is hard to write. That's design feedback. Refactor the design first; the test gets easier.

It's the wrong tool when:

  • You're rewriting because you don't like the style. Personal taste isn't a refactoring case. The Boy Scout Rule covers small style improvements; large-scale stylistic rewrites are usually not worth the disruption.

  • The deadline is tomorrow. Refactoring takes time and can introduce subtle bugs. If you're under fire, get the feature shipped and refactor afterward.

Pitfalls

Refactoring that secretly changes behavior. A "rename" that also tweaks an edge case. An "extract method" that drops a null check. If behavior changed, the refactoring was a feature change in disguise, and the tests will tell you if you run them.

Big-bang refactors. If you can't review the diff in one sitting, it wasn't a refactoring, it was a rewrite.

Improvements that aren't. A value object with no validation, a class split that nobody needed, an interface with one implementation nobody plans to swap. The structural change has to be a real improvement, not just a different shape.

The one thing to remember

Refactoring is a small, behavior-preserving, test-supported practice that takes a green test suite and a decision to wear one hat at a time.

The patterns, value objects and repositories earlier in the course all make a codebase easier to refactor. With an honest suite, refactoring becomes part of the daily rhythm instead of a special project.

Course Content