Back

Activity 2.6: Refactoring

divider

Activity 2.6

Refactoring

Key Concepts

Changing Shape, Not Behavior

Spotting the Repeat

Extracting a Method

Proving Nothing Changed

Every Method So Far Was Planned Before the Code Existed

In Activities 2.1 through 2.5, the method came first: a task told you what Haul or DrawBuilding should do, and you wrote it.

Real programs do not usually grow that way. Somebody copies a block that works, pastes it, and changes two numbers. Then does it again. By the time anyone notices, the program is a wall of near-identical blocks. Today is about turning that wall into methods after the fact, without breaking anything.

Refactoring Changes Shape, Not Behavior

Refactoring is changing how code is written without changing what it does. Same inputs, same outputs, different shape.

If the behavior changed, you did not refactor. You edited. That is not a ban on editing — it is a reason to do the two separately, so you always know which kind of change you are making.

The College Board Names This Exact Freedom

The course framework says procedural abstraction lets programmers “change the internals of the procedure (to make it faster, more efficient, use less storage, etc.) without needing to notify users of the change as long as what the procedure does is preserved.”

“As long as what the procedure does is preserved” is the definition of refactoring in one line. It is also the part people skip checking.

Two Blocks, Different Values

Here is a program that reports two students' scores. Someone wrote the first block, copied it, and edited the copy. As you read it, find every place the two blocks differ.

Two Blocks, Different Values

Demo
string aName = "Avery";
int aScore = 88;
string aVerdict = "fail";
if (aScore >= 60)
{
aVerdict = "pass";
}
Console.WriteLine($"{aName}: {aScore} ({aVerdict})");
string bName = "Blake";
int bScore = 42;
string bVerdict = "fail";
if (bScore >= 60)
{
bVerdict = "pass";
}
Console.WriteLine($"{bName}: {bScore} ({bVerdict})");

Two Blocks, Different Values

The structure is identical: a name, a score, a verdict that starts as "fail", an if that may change it, and a line of output.

The only real differences are two values: the name and the score. The variable names differ too, but only because each copy needed names that did not clash.

That is the smell. Length is not the giveaway; blocks that differ only in values are.

Differences Become Parameters

The move: whatever differed between the copies becomes a parameter, and whatever stayed the same becomes the method's body. The name and the score become ReportLine(string name, int score), and each block becomes one call.

Predict the output. It should be the same as before. Is it?

Differences Become Parameters

Demo
ReportLine("Avery", 88);
ReportLine("Blake", 42);
void ReportLine(string name, int score)
{
string verdict = "fail";
if (score >= 60)
{
verdict = "pass";
}
Console.WriteLine($"{name}: {score} ({verdict})");
}
Demo
Avery: 88 (pass)
Blake: 42 (fail)

Differences Become Parameters

Character for character, the same two lines. Seventeen lines became thirteen, and a third student is now one line instead of eight more.

The bigger win is the next change. If the pass mark moves from 60 to 65, there is now one place to change it. In the copied version there were two, and with thirty students there would be thirty — and missing one would be easy.

A Recipe You Can Follow

  1. Run the program and record its exact output.
  2. Find blocks that differ only in values.
  3. Write down what differs. Those are your parameters.
  4. Move the shared code into a method.
  5. Replace each block with a call.
  6. Run it again and compare to the recording.

Record the Output Before You Touch Anything

Refactoring is defined by the output not changing, so the only way to know you refactored is to compare. And you can only compare against something you saved before you started.

Activity 1.4's block comment is perfect for this. Paste the old output between /* and */ at the bottom of the file, where it does nothing to the program but stays in view.

Record the Output Before You Touch Anything

Demo
ReportLine("Avery", 88);
ReportLine("Blake", 42);
/* Output before refactoring:
Avery: 88 (pass)
Blake: 42 (fail)
*/

Do not rebuild the recording from the new code. Working out “what it should print” from the refactored version checks the new code against itself, which proves nothing.

Matching Today Is Not the Same Behavior

Suppose someone “tidies” ReportLine and the pass mark ends up at 50 instead of 60. They run it with Avery and Blake, and the output matches the recording exactly.

Demo
if (score >= 50)
{
verdict = "pass";
}

Is that a refactor? Think of a student who would expose it.

Matching Today Is Not the Same Behavior

Add a third student who scored 55, and run both versions.

Demo
ReportLine("Avery", 88);
ReportLine("Blake", 42);
ReportLine("Casey", 55);
Pass mark 60
Avery: 88 (pass)
Blake: 42 (fail)
Casey: 55 (fail)
Pass mark 50
Avery: 88 (pass)
Blake: 42 (fail)
Casey: 55 (pass)

Matching Today Is Not the Same Behavior

Casey passes in one and fails in the other. Avery and Blake could never tell the two apart, because 88 and 42 land on the same side of both 50 and 60.

“Behavior did not change” means for every input, not just the ones you tried. The inputs that catch a changed rule are the ones near the rule's boundary — the same lesson Activity 2.3's Status taught about testing one value per band.

Not Every Repeat Is Worth a Method

Three gauges, one line each. They differ only in values, so they could become a method:

Demo
Console.WriteLine($"Fuel: {fuel}%");
Console.WriteLine($"Oxygen: {oxygen}%");
Console.WriteLine($"Power: {power}%");
Demo
void Gauge(string label, int value)
{
Console.WriteLine($"{label}: {value}%");
}

Not Every Repeat Is Worth a Method

Three one-line prints became a one-line method plus three calls. The program got longer, and anyone reading it now has to jump to Gauge to see what a line prints.

Worth it if there will be twenty gauges, or if every gauge is about to get a warning when it runs low. Not worth it for three that will never change. This is judgment, not a rule, and you will be asked to defend yours.

Today's Objectives

  • Defining refactoring as changing structure without changing behavior
  • Finding repeated blocks that differ only in values
  • Extracting a method and replacing the repeats with calls
  • Proving the output is unchanged, including at the boundaries

Key Terms

Refactoring
Changing how code is written without changing what it does.
Extract a method
Move repeated code into a named method and replace each copy with a call.
Regression
A change that was supposed to be safe and broke something.

'F' → Fullscreen

divider

Build

Today you inherit someone else's program, named 2-6-monster-cards. It prints trading cards for a monster game, and whoever wrote it built every card by copying the one above. Your job is to turn it into a method without changing a single character of what it prints — and then to find out whether the program was right in the first place.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign. Your Task 1 comment sits below the last line shown and is not repeated.


Task 1: Record the Before

  • Write the code below exactly as shown, copy-paste style and all. Each card is a name, an attack, a defense, a power that adds them, and a rarity: RARE at 10 or more.
  • Run it. Copy the exact output into a block comment at the bottom of the file, between /* and */, the way the deck showed. You will compare against it in Task 2.
  • Look at the three blocks and write down what differs between them: those will be your parameters.
2-6-monster-cards
string name1 = "Glimmerfang";
int attack1 = 7;
int defense1 = 3;
int power1 = attack1 + defense1;
Console.WriteLine($"=== {name1} ===");
Console.WriteLine($" ATK {attack1} DEF {defense1} POWER {power1}");
if (power1 >= 10)
{
Console.WriteLine(" Rarity: RARE");
}
else
{
Console.WriteLine(" Rarity: common");
}
string name2 = "Mossback";
int attack2 = 2;
int defense2 = 6;
int power2 = attack2 + defense2;
Console.WriteLine($"=== {name2} ===");
Console.WriteLine($" ATK {attack2} DEF {defense2} POWER {power2}");
if (power2 >= 10)
{
Console.WriteLine(" Rarity: RARE");
}
else
{
Console.WriteLine(" Rarity: common");
}
string name3 = "Emberwyrm";
int attack3 = 9;
int defense3 = 4;
int power3 = attack3 + defense2;
Console.WriteLine($"=== {name3} ===");
Console.WriteLine($" ATK {attack3} DEF {defense3} POWER {power3}");
if (power3 >= 10)
{
Console.WriteLine(" Rarity: RARE");
}
else
{
Console.WriteLine(" Rarity: common");
}

Task 2: Extract the Method

  • Replace all three blocks with the version below: one PrintCard method and three calls. Keep your comment.
  • Run it and compare to your comment, line by line. One line will not match.
  • Work out which program is right — the old one or the new one — by doing the card's arithmetic by hand. Then find the exact line in the Task 1 code that caused the difference, and write down its line number and what was wrong with it.
2-6-monster-cards
PrintCard("Glimmerfang", 7, 3);
PrintCard("Mossback", 2, 6);
PrintCard("Emberwyrm", 9, 4);
void PrintCard(string name, int attack, int defense)
{
int power = attack + defense;
Console.WriteLine($"=== {name} ===");
Console.WriteLine($" ATK {attack} DEF {defense} POWER {power}");
if (power >= 10)
{
Console.WriteLine(" Rarity: RARE");
}
else
{
Console.WriteLine(" Rarity: common");
}
}

Task 3: The Payoff

  • Two new monsters join the game. In the copy-paste version, each would have been fourteen more lines. Now each is one: add lines 4 and 5.
  • The game designers add a new rarity, LEGENDARY, for a power of 15 or more. Add it as shown, checking the highest band first, the way Activity 2.3's Status did. Count how many places you had to change.
  • Run it and check every card's rarity by hand.
2-6-monster-cards
PrintCard("Glimmerfang", 7, 3);
PrintCard("Mossback", 2, 6);
PrintCard("Emberwyrm", 9, 4);
PrintCard("Voltlynx", 8, 8);
PrintCard("Pebblet", 1, 1);
void PrintCard(string name, int attack, int defense)
{
int power = attack + defense;
Console.WriteLine($"=== {name} ===");
Console.WriteLine($" ATK {attack} DEF {defense} POWER {power}");
if (power >= 15)
{
Console.WriteLine(" Rarity: LEGENDARY");
}
else if (power >= 10)
{
Console.WriteLine(" Rarity: RARE");
}
else
{
Console.WriteLine(" Rarity: common");
}
}

Task 4: Two Tidy-Ups, One Refactor

Two classmates each “tidied” the LEGENDARY check and swear nothing changed. Try each one in your program, one at a time, and record the output.

  1. Riley changed power >= 15 to power > 14.
  2. Sam changed power >= 15 to power > 15.

With the five cards you have, both match your Task 3 output exactly. Now add one more monster, PrintCard("Tidecrown", 10, 5);, and run all three versions again: yours, Riley's, and Sam's.

Say which tidy-up is a true refactor and which is not, and explain why the five original cards could not tell them apart. Is there any whole number of power where Riley's version would give a different rarity from yours?

There is no code block for this task. When it is over, put power >= 15 back and keep Tidecrown: your program is Task 3 with a sixth card.


Challenge (Optional): Refactor Something Older

  • Pick a Quarter 1 program of yours that repeats itself. Record its exact output in a comment, extract a method, and confirm the output matches character for character.
  • If the program asks for input, you must type exactly the same answers both times, or the comparison means nothing. Write down the answers you used.
divider

Checkpoint

Your finished program, with Tidecrown added, prints exactly this.

Example Output
=== Glimmerfang ===
ATK 7 DEF 3 POWER 10
Rarity: RARE
=== Mossback ===
ATK 2 DEF 6 POWER 8
Rarity: common
=== Emberwyrm ===
ATK 9 DEF 4 POWER 13
Rarity: RARE
=== Voltlynx ===
ATK 8 DEF 8 POWER 16
Rarity: LEGENDARY
=== Pebblet ===
ATK 1 DEF 1 POWER 2
Rarity: common
=== Tidecrown ===
ATK 10 DEF 5 POWER 15
Rarity: LEGENDARY
  • One PrintCard method prints every card, and it is below the main program
  • Adding a monster is one line, and LEGENDARY was one change in one place
  • Your Task 1 output is saved in a comment, and you recorded which line of the Task 1 program was wrong
  • You recorded all three Task 4 runs with Tidecrown and which tidy-up is a refactor
divider

Reflection

Answer the following questions before submitting your work.

  1. Refactoring means behavior does not change. How did you check that in Task 2, rather than assume it?
  2. Emberwyrm's card changed in Task 2. Was the Task 2 change a refactor? Explain what the Task 1 program got wrong, and why PrintCard cannot make that mistake.
  3. Sam's version matched all five cards and was still not a refactor. Why could those five cards not catch it, and what kind of test value did?
divider

Submit

Submit four things to the dropbox:

  1. Your 2-6-monster-cards program file, with your Task 1 output comment still at the bottom.
  2. What differed between the three Task 1 blocks, and the wrong line you found in Task 2 with what was wrong with it.
  3. How many places LEGENDARY took, and your Task 4 results with which tidy-up is a refactor.
  4. Your three reflection answers.

Activity Complete