Refactor
Stage 4 starts with something that already works and asks the learner to make it better. The task shifts from achieving basic functionality to evaluating quality, identifying weaknesses, and improving the solution according to the conventions and constraints of the target technical ecosystem.
Concept: Conditional Branching (if, elif, else)
Dataset detected: NO. Generating dummy data.
Hi, the Junior sent this over. Incredibly, it actually works and produces the correct output, but my eyes are bleeding reading it. Please refactor it before it hits production.
🚨 Your objective in this lesson: You must copy the code blocks from each Challenge exactly as they are and paste them into your IDE, then refactor the code by rewriting it professionally until you achieve the exact Program Output when running the refactored program.
Challenge 1️⃣: Tax Bracket Calculator
This script iterates through a list of income values and calculates the required tax amount based on predefined brackets, but uses terrible nested logic and redundant type casting instead of a clean if/elif/else chain.
💩 Dirty Code:
lst = [15000.0, 45000.0, 95000.0, 200000.0]
for val in lst:
v = float(val)
res = 0.0
if v < 20000.0:
res = v * 0.05
else:
if v >= 20000.0 and v < 50000.0:
res = v * 0.10
elif v >= 50000.0 and v < 100000.0:
res = v * 0.15
else:
if v >= 100000.0:
res = v * 0.25
print(f"Income: ${v:,.2f} -> Tax: ${res:,.2f}")
💻 Program Output:
Income: $15,000.00 -> Tax: $750.00 Income: $45,000.00 -> Tax: $4,500.00 Income: $95,000.00 -> Tax: $14,250.00 Income: $200,000.00 -> Tax: $50,000.00
Challenge 2️⃣: Subscription Tier Benefits
This code assigns features and monthly costs based on string names of subscription tiers. It suffers from duplicate condition checks, unnecessary intermediate variables, and inconsistent string normalization.
💩 Dirty Code:
usR_liST = ["basic", "PREMIUM", "vip", "None"]
for u in usR_liST:
a1 = str(u).lower()
b2 = ""
if a1 == "basic":
b2 = "Standard Ads"
elif a1 == "premium":
b2 = "No Ads + HD"
elif a1 == "vip":
b2 = "No Ads + 4K + Downloads"
elif a1 == "none":
b2 = "Guest Mode"
else:
b2 = "Guest Mode"
c3 = float(0)
if a1 == "vip":
c3 = 19.99
elif a1 == "premium":
c3 = 9.99
else:
c3 = 0.00
print(f"User: {u} | Benefits: {b2} | Cost: ${c3:,.2f}")
💻 Program Output:
User: basic | Benefits: Standard Ads | Cost: $0.00 User: PREMIUM | Benefits: No Ads + HD | Cost: $9.99 User: vip | Benefits: No Ads + 4K + Downloads | Cost: $19.99 User: None | Benefits: Guest Mode | Cost: $0.00
Challenge 3️⃣: Sensor Priority Router
This script evaluates sensor temperature data to trigger hardware alerts and assign potential maintenance costs. It uses over-complicated boolean checks (== True), deep nesting, and confusing abbreviations.
💩 Dirty Code:
s_d = [{"t": 95, "m": True}, {"t": 40, "m": False}, {"t": 110, "m": True}, {"t": 10, "m": False}]
for tmp_dict in s_d:
t_val = int(tmp_dict["t"])
m_val = bool(tmp_dict["m"])
stat = ""
p = 0.0
if t_val > 100 and m_val == True:
stat = "CRITICAL SHUTDOWN"
p = 5000.00
elif t_val > 100 and m_val == False:
stat = "OVERHEAT WARNING"
p = 1000.00
else:
if t_val > 80:
stat = "MAINTENANCE CHECK"
p = 250.00
else:
stat = "SYSTEM OPTIMAL"
p = 0.00
print(f"Sensor Temp: {t_val} -> Status: {stat} | Cost: ${p:,.2f}")
💻 Program Output:
Sensor Temp: 95 -> Status: MAINTENANCE CHECK | Cost: $250.00 Sensor Temp: 40 -> Status: SYSTEM OPTIMAL | Cost: $0.00 Sensor Temp: 110 -> Status: CRITICAL SHUTDOWN | Cost: $5,000.00 Sensor Temp: 10 -> Status: SYSTEM OPTIMAL | Cost: $0.00
Challenge 4️⃣: E-Commerce Discount Calculator
This program applies dynamic pricing rules based on the cart total and user membership level. The code is highly verbose, repeats mathematical operations, and features erratic casing for variable names.
💩 Dirty Code:
carTs = [ {"v": "150.50", "mem": "GOLD"}, {"v": "45.00", "mem": "SILVER"}, {"v": "250.00", "mem": "NONE"}, {"v": "5.00", "mem": "GOLD"} ]
for c_i in carTs:
amT = float(str(c_i["v"]))
tYpE = str(c_i["mem"])
f_aMt = 0.0
if amT >= 100.00:
if tYpE == "GOLD":
f_aMt = amT - (amT * 0.20)
elif tYpE == "SILVER":
f_aMt = amT - (amT * 0.10)
else:
f_aMt = amT - (amT * 0.05)
elif amT >= 50.00:
if tYpE == "GOLD":
f_aMt = amT - (amT * 0.10)
else:
f_aMt = amT
else:
f_aMt = amT
s = f_aMt
print(f"Original: ${amT:,.2f} | Member: {tYpE} | Final Price: ${s:,.2f}")
💻 Program Output:
Original: $150.50 | Member: GOLD | Final Price: $120.40 Original: $45.00 | Member: SILVER | Final Price: $45.00 Original: $250.00 | Member: NONE | Final Price: $237.50 Original: $5.00 | Member: GOLD | Final Price: $5.00
⚡ Coding5s System – Learn Programming by Writing Code – Coding5S.com
