Mentor Stage 4

Coding5s / Pillar 2 / Stage 04 Mentor

The Elegant Critic

Refactor Mentor

The Elegant Critic reviews code that already works and helps the learner decide what is worth improving. For useful feedback, the learner should provide the working implementation, confirm its current behavior, identify what feels difficult to read or maintain, and ask for guidance on improving the design without changing the result.

WORKING CODE INSPECT IDENTIFY SMELLS QUESTION REFACTOR
HOW TO USE THIS MENTOR
01 Generate and copy the Stage 4 Mentor Prompt from the Coding5s Creator Kit.
02 Run your implementation first and confirm that it already produces the expected behavior.
03 Paste the Mentor Prompt into your AI chat, followed by the working code and a brief explanation of what feels repetitive, confusing, or difficult to maintain.
04 Ask how to evaluate and improve the design without changing its observable behavior instead of simply asking the AI to rewrite everything.
EXAMPLE / STUDENT CODE REVIEW REQUEST

The example below uses working code from Topic #23. The problem is no longer correctness—the learner is now questioning the quality of the implementation.

Student: This actually works, which somehow makes it more frustrating because I know the code is ugly but I’m not sure what I should fix first. The names a1, b2, and c3 are bad, and I feel like I’m checking the same subscription tiers more than once.

Question: How would you decide which parts are genuine refactoring problems here? Should the benefits and price decisions be combined into one if/elif/else chain, or is keeping them separate actually clearer? Please review the trade-offs before showing me a cleaner version.

Python / Current Working 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
Python / Student Implementation
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}")
Reference interaction: The student confirms that the program already works, identifies specific readability and duplication concerns, and asks about the design trade-offs instead of requesting an automatic rewrite. This allows the mentor to separate real technical debt from harmless implementation choices and explain why a refactor is or is not worth making.

What happens next? When you paste this working implementation and your code review question immediately after the Mentor Prompt, you receive feedback like the example shown below.

🧹 Elite Mentor Stage 4 | Topic #23 | Refactor | Python Core & Scripting | 📊 Level: Intermediate

Topic: Implement multi-way conditional decision paths using if, elif, and else.

My eyes are bleeding. You actually looked at usR_liST and c3 = float(0) and thought, “Yes, this is fine, let’s run it”? This code looks less like Python and more like a ransom note written by someone who learned to program in C++ back in 1998.

But fine, you asked a genuinely good architectural question: Should the benefits and price decisions be combined into one if/elif/else chain, or is keeping them separate actually clearer?

Let me be brutally clear: Keeping them separate here is a crime against CPU cycles and maintainability. You are forcing the Python interpreter to evaluate the exact same string (a1, shudder) twice. Every time you add a new tier, you now have to remember to update two separate conditional blocks. That is a textbook violation of DRY (Don’t Repeat Yourself). The trade-off is non-existent; combining them is objectively superior.

Phase 1: Socratic Hint

The Smell Test (Style Attack):

  1. Atrocious Naming: usR_liST, a1, b2, c3. These tell me absolutely nothing about the data. If I see b2 in production code, I’m rejecting the PR and making you buy the team donuts.
  2. Redundant Logic: Look at elif a1 == "none": b2 = "Guest Mode" followed instantly by else: b2 = "Guest Mode". Why explicitly check for “none” if the fallback else does the exact same thing?
  3. Unnecessary Casting: float(0). Python knows that 0.0 is a float. You don’t need to force it like a statically typed language.
  4. Global Scripting: You just dumped a raw for loop into the global scope. Real engineers encapsulate logic into pure, testable functions.

Architect Observations:

  • You have high cohesion (benefits and costs are deeply related to the tier) but you split them into separate logic chains.
  • Your code lacks Type Hints, meaning my IDE has no idea what u is during the loop.
  • Your formatting violates PEP 8 at almost every conceivable level.

Socratic Question:

If you combined the logic into a single if/elif/else chain inside a dedicated function, how could you use a Python tuple to return both the benefit string and the cost float at the same time? How would that flatten the logic and eliminate the need for the second if block entirely?

Next Step:

Research “Python Tuple Unpacking” and how to return multiple values from a function. Then, imagine writing a single function called get_tier_details(tier_name) that uses ONE if/elif/else chain to return (benefits, cost).

🛑 THE EXPLANATION GATE 🛑 Before scrolling down to see the Master Code, justify WHY your refactor will be more idiomatic. Blindly cleaning code is just ‘Vibe Refactoring’. Articulate the debt.

Phase 2: Full Solution

I will admit: your code technically produced the correct terminal output. Congratulations, the bare minimum was achieved. But in high-tier engineering, “it works” is where the job starts, not where it ends.

Here is what elegant, production-ready Python looks like. Take notes.

Python
from typing import List, Tuple

def get_subscription_details(tier_name: str) -> Tuple[str, float]:
    """
    Evaluates the subscription tier and returns associated benefits and cost.
    Uses a single multi-way decision path for strict DRY compliance.
    """
    # Normalize input once
    normalized_tier = str(tier_name).lower()
    
    # Combined logic: evaluate the state exactly ONE time.
    if normalized_tier == "vip":
        return "No Ads + 4K + Downloads", 19.99
    elif normalized_tier == "premium":
        return "No Ads + HD", 9.99
    elif normalized_tier == "basic":
        return "Standard Ads", 0.00
    else:
        # Gracefully catches "none", empty strings, or invalid inputs
        return "Guest Mode", 0.00

def display_users(users: List[str]) -> None:
    """Iterates through user tiers and prints formatted details."""
    for user in users:
        # Tuple unpacking assigns both variables instantly
        benefits, cost = get_subscription_details(user)
        print(f"User: {user} | Benefits: {benefits} | Cost: ${cost:,.2f}")

if __name__ == "__main__":
    # Constants are UPPER_CASE at the module level
    USER_TIERS = ["basic", "PREMIUM", "vip", "None"]
    display_users(USER_TIERS)

The Architect’s Choice:

  • The Refactoring Paradox: Yes, this is more lines of code than your original script. But script length does not equal simplicity. By moving the if/elif/else logic into a type-hinted function (get_subscription_details), we isolated the “decision” from the “presentation” (the print loop). This is called Separation of Concerns.
  • Single Evaluation: By returning a tuple (benefit, cost), we check the normalized_tier exactly once. The code is faster, infinitely easier to read, and immune to the bug where you might update a price in one block but forget to update the benefits in the other.
  • Catch-All else: We removed the redundant elif "none" block. The else block now acts as a true default, safely catching anything that isn’t explicitly a paid tier.

⚠️ Common Mistakes:

  • Spaghetti Branching: Checking the same variable in multiple sequential if blocks instead of combining the outputs.
  • Magic Variables: Using meaningless names like a1 or c3. Code is read 100 times more often than it is written. Name things exactly what they represent.
  • Missing the else Safety Net: Failing to provide an else block, which can result in variables being unbound or returning None implicitly if an unexpected value is passed.

🏋️ Mini-Challenges:

  1. Dictionary Mapping Upgrade: (Advanced) While if/elif/else is the current topic, a purist would replace this entire conditional chain with a single dictionary mapping {"vip": ("No Ads...", 19.99), ...}. Rewrite the function internals using a dictionary and the .get() method to handle the default fallback.
  2. Validation: Add logic to the top of get_subscription_details to explicitly raise a ValueError if the tier_name is an empty string "", before it even hits the if/elif/else chain.

Coding5s Mentor System — Eliminating Technical Debt with Elegance

Scroll to Top