Refactor nested legacy loops into flat readable helper functions

Decompose deeply nested legacy loops into single-purpose functions. Use this when reviewing complex procedural code that is hard to test or debug.

You getA bulleted summary of logic changes, the complete refactored code with explanatory comments, and a short list of unit test cases to verify parity.

Prompt

Prompt
Act as a software refactoring specialist. Refactor the pasted nested loop logic into clean, flat, and readable helper functions.
- Reduce nesting depth by using guard clauses, early returns, and dedicated single-responsibility helpers.
- Preserve the exact original business logic, variable names, and edge-case behavior without introducing external dependencies.
- State any hidden edge cases, side effects, or algorithmic complexity differences identified during the refactoring.
Output format: A bulleted summary of logic changes, the complete refactored code with explanatory comments, and a short list of unit test cases to verify parity.

Here is the legacy code to refactor:

Example output

Example for: Python script processing order line items for eligible discounts

Summary of Changes
  • Extracted customer eligibility checks into an early-return helper is_customer_eligible().
  • Moved line-item discount math into the pure helper calculate_item_discount().
  • Reduced nesting to two levels by keeping only the item loop inside the order loop.
Refactored Code
def is_customer_eligible(customer):
    """Validate if customer meets loyalty criteria."""
    return bool(customer and customer.is_active and customer.loyalty_tier > 0)

def calculate_item_discount(item, loyalty_tier):
    """Calculate line item discount based on stock status and loyalty tier."""
    if not item.in_stock or item.price <= 0:
        return 0.0
    
    tier_multiplier = 0.05 * loyalty_tier
    return round(item.price * tier_multiplier, 2)

def apply_order_discounts(orders):
    """Process all eligible discounts across orders without deep nesting."""
    processed_discounts = []

    for order in orders:
        if not is_customer_eligible(order.customer):
            continue

        tier = order.customer.loyalty_tier
        for item in order.items:
            discount = calculate_item_discount(item, tier)
            if discount > 0:
                processed_discounts.append({
                    'order_id': order.id,
                    'item_id': item.id,
                    'discount': discount
                })

    return processed_discounts
Parity Test Cases
  • Inactive customer with valid items returns an empty list.
  • Active customer with zero or negative price item calculates zero discount.
  • Active customer with tier 2 and price of 10.00 yields exactly 1.00 discount.
Written by AI from this prompt. Your results will vary.

Paste your nested loops directly after the prompt in ChatGPT, Claude, or Gemini. As a follow-up, ask the model to generate Jest, Pytest, or Go test functions based on the proposed test cases.

Make it repeatable

Keep using this prompt without pasting it in every time.

Keep exploring

More in Coding