Skip to content

Examples Used

Jk edited this page Mar 19, 2026 · 1 revision

Examples Used

This page indexes all code examples used in the induction program — where they appear, what concept they illustrate, and why they were chosen over alternatives.


Index

# Example Module Language Concept
1 fetch_user_profile Engineering Principles Python Input validation + clean return shape
2 calculate_total_price TDD Workflow Python Full Red→Green cycle with edge cases
3 create_task (API) API Design Python API contract: validation + structured error
4 createTask (frontend) System Thinking JavaScript End-to-end fetch with error handling
5 update_task_status (broken) PR Review Python Missing null check + enum validation
6 process_order (broken) PR Review Python KeyError + range validation gap
7 Environment config Deployment Python os.getenv + startup guard

Detailed Notes


1 · fetch_user_profile — Input Validation

Appears in: Module 05 (Implementation) Source: AI_FullStack_Induction_v2.pdf — Section 2

def fetch_user_profile(user_id):
    if not isinstance(user_id, int):
        raise ValueError("Invalid user_id")
    user = get_user_from_db(user_id)
    if not user:
        return None
    return {
        "id": user["id"],
        "name": user["name"],
        "email": user["email"]
    }

Why this example:

  • Shows two distinct validation points: type check on input, null check on DB result
  • The explicit return shape ({"id", "name", "email"}) models the principle of not leaking raw DB objects to callers
  • Short enough to read in one pass; complex enough to be realistic

What it teaches:

  • Validate at the entry point, not deep in the call stack
  • Null checks are not optional
  • Return shapes should be deliberate contracts

2 · calculate_total_price — TDD Red/Green Cycle

Appears in: Module 06 (TDD in Practice) Source: AI_FullStack_Induction_v2.pdf — Section 3

# Test first (RED):
def test_calculate_total_price():
    items = [{"price": 100, "quantity": 2}]
    result = calculate_total_price(items, 0.1)
    assert result == 180

def test_invalid_price_raises():
    items = [{"price": -10, "quantity": 1}]
    with pytest.raises(ValueError):
        calculate_total_price(items, 0)

# Implementation (GREEN):
def calculate_total_price(items, discount):
    if not 0 <= discount <= 1:
        raise ValueError("Invalid discount")
    total = 0
    for item in items:
        if item["price"] < 0 or item["quantity"] <= 0:
            raise ValueError("Invalid values")
        total += item["price"] * item["quantity"]
    return int(total * (1 - discount))

Why this example:

  • The arithmetic is simple enough that the reader can verify correctness mentally (100 * 2 * 0.9 = 180)
  • Demonstrates both the happy path test and a negative test (pytest.raises)
  • The discount range check (0 <= discount <= 1) is a realistic business rule that is easy to forget

What it teaches:

  • Tests define expected behaviour before implementation exists
  • Both happy path and error path need tests
  • Discount as a decimal (0.1 = 10%) is a common source of bugs — the range check catches misuse

3 · create_task — API Contract

Appears in: Module 05 (API Design in Practice) Source: AI_FullStack_Induction_v2.pdf — Section 4

def create_task(request_json):
    title = request_json.get("title")
    if not title or not isinstance(title, str):
        return {
            "error":  "INVALID_INPUT",
            "field":  "title",
            "detail": "title is required"
        }, 400
    task_id = save_task(title.strip())
    return {"id": task_id, "status": "created"}, 201

Why this example:

  • Demonstrates the complete API contract pattern: validation → structured error → success response → HTTP status code
  • The three-field error format (error, field, detail) is a realistic, commonly used pattern
  • title.strip() models sanitisation as distinct from validation
  • 201 vs 200 is a real distinction worth teaching (resource created vs generic OK)

Contrast with the broken version (from Graded_Debugging_Challenge_v2.pdf):

# ❌ Missing: type check, .strip(), HTTP status code
def create_task(data):
    task = {"id": generate_id(), "title": data["title"], ...}
    save_task(task)
    return task

The gap between these two versions is the core learning of the PR Review module.


4 · createTask — Frontend Fetch

Appears in: Module 01 (Full-Stack Thinking) Source: AI_FullStack_Induction_v2.pdf — Section 5

async function createTask(task) {
    const response = await fetch("/api/tasks", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(task)
    });
    if (!response.ok) {
        throw new Error("Request failed");
    }
    return await response.json();
}

Why this example:

  • Deliberately simple — the point is not the JavaScript, it is the system layer it represents
  • Used to anchor the Frontend → API layer contract in the system diagram
  • response.ok check models that the frontend must handle API errors, not assume success

Extension opportunity: Replace throw new Error("Request failed") with a structured error handler that reads response.json() and surfaces the error/detail fields from the API contract — this connects Module 01 to Module 05.


5 + 6 · PR Review Examples — Intentionally Broken Code

Appears in: Module 07 (PR Review Simulation) Source: Graded_Debugging_Challenge_v2.pdf — Starter Code

# update_task_status — issues: no null check, no status validation, no HTTP code
def update_task_status(task_id, status):
    task = fetch_task(task_id)     # ① no null check
    task["status"] = status        # ② no enum validation
    update_task(task)
    return task                    # ③ no HTTP status code

# process_order — issues: KeyError risk, no discount range check
def process_order(order):
    total = 0
    for item in order["items"]:    # ④ KeyError if missing
        total += item["price"] * item["qty"]
    if order.get("discount"):
        total -= total * order["discount"]  # ⑤ no range check
    return total

Why this example:

  • Sourced directly from the Graded Debugging Challenge — interns will encounter this exact code
  • The five issues span four categories: null safety, validation, API contract, and input safety
  • The issues are realistic — they are the actual mistakes junior developers make, not contrived errors
  • The VALID_STATUSES constant being defined but never used is a particularly realistic detail (it suggests the author intended to validate but forgot)

Pedagogic note: The visual annotation (underline wavy styling in the HTML) is deliberate — it mirrors how an IDE would highlight errors, priming interns to read code the way a linter reads it.


7 · Environment Config — Deployment

Appears in: Module 10 (Deployment Awareness) Source: AI_FullStack_Induction_v2.pdf — Section 9

import os
DB_HOST = os.getenv("DB_HOST")
if not DB_HOST:
    raise RuntimeError("Missing DB config")

Why this example:

  • The startup guard (raise RuntimeError) is the key teaching point: fail fast and loudly on missing config, not silently at runtime when a query fails
  • One of the shortest examples in the program, which is appropriate — deployment awareness is not about code complexity, it is about operational discipline
  • The os.getenv pattern is language-agnostic enough that its equivalents in Go (os.Getenv) or Node.js (process.env) are immediately recognisable

Candidate Examples for Future Modules

These examples were considered but not included in v2:

Example Concept Why deferred
Database migration script Schema versioning Requires more context on DB tooling (Alembic, Flyway)
JWT middleware Authentication Too specific to auth patterns; may not apply to all projects
React component with props Frontend state Would require more frontend-specific content to contextualise
Go HTTP handler Multi-language support Would duplicate the Python API example; better as a language variant
Dockerfile Containerisation Important but belongs in a Deployment deep-dive module

Clone this wiki locally