Refactor while Preserving Observable Behavior
Core idea
Refactoring changes internal structure without intentionally changing observable behavior. First capture the current contract with regression tests. Make small changes and rerun tests after each step. Compare outputs, exceptions and relevant side effects; passing a small suite is evidence, not proof of equivalence for every input.
def old(n): return n*5 + 2def base(n): return n*5def new(n): return base(n) + 2print(all(old(n)==new(n) for n in range(6)))The bounded comparison checks six nonnegative inputs; extracting the rule clarifies its role.
Expected output:
TruePreserve rejection behavior
def before(n): if n < 0: raise ValueError('negative') return n*2def checked(n): if n < 0: raise ValueError('negative') return ndef after(n): return checked(n)*2for fn in (before, after): try: fn(-1) except ValueError as exc: print(str(exc))Both versions preserve the relevant exception type and message for the sampled case.
Expected output:
negativenegativeCommon mistake
Do not change requirements and refactor at the same time without distinguishing the changes. A shorter function can still lose edge-case behavior.
Practice
Extract a validation function from an existing rule. Run tests for valid, zero and invalid inputs before and after the change; record any intentional behavior change separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Refactoring
Check your understanding of refactoring.
What is printed?
def a(n): return n+2def b(n): return 2+nprint(a(3)==b(3))What is printed?
def f(n): return n>0print(f(0))What should refactoring preserve?
What is the value of regression tests before refactoring?