Chapter 34 Exercises: Managing Technical Debt
Tier 1: Recall and Recognition (Exercises 1-6)
Exercise 1: Debt Pattern Identification
Objective: Recall the seven AI-specific debt patterns.
List all seven AI-specific debt patterns described in Section 34.2 from memory. For each pattern, write a one-sentence description explaining what makes it distinct from the others.
Exercise 2: Vocabulary Matching
Objective: Match technical debt terms to their definitions.
Match each term on the left with its correct definition on the right:
| Term | Definition | |
|---|---|---|
| 1. SQALE | A. The ratio of remediation cost to rewrite cost | |
| 2. Technical Debt Ratio | B. A metric for human comprehension difficulty of code | |
| 3. Cyclomatic complexity | C. A structured inventory of known debt items | |
| 4. Cognitive complexity | D. A method for measuring technical debt based on quality characteristics | |
| 5. Debt catalog | E. The number of independent execution paths through code |
Exercise 3: Decision Tree Application
Objective: Apply the debt decision framework to simple scenarios.
For each scenario, trace through the decision tree from Section 34.8 and state what action should be taken:
- A dependency with a known CVE (security vulnerability) is used in the authentication module.
- Two functions in the same file have slightly different formatting styles.
- Three different modules implement their own date parsing logic, and you are about to add a fourth module that needs date parsing.
- A module uses a deprecated API that still works and is in a rarely-modified area of code.
- Your configuration loader uses the Abstract Factory, Strategy, and Builder patterns to read a single JSON file.
Exercise 4: Metric Classification
Objective: Categorize code quality metrics by what they measure.
Classify each metric as primarily measuring complexity, consistency, coupling, or duplication:
- Cyclomatic complexity
- Pattern consistency score
- Afferent coupling
- Code duplication percentage
- Cognitive complexity
- Efferent coupling
- Abstraction deficit
- Maintainability index
Exercise 5: Stakeholder Translation
Objective: Recall the principles of communicating debt to non-technical stakeholders.
Identify which of the following statements are appropriate for a stakeholder debt report and which are not. Explain why for each:
- "Our cyclomatic complexity average has risen to 14.3."
- "Feature delivery has slowed by 25% due to code inconsistencies."
- "The AI wrote terrible code and we need to fix it."
- "We have identified a security risk that could expose customer data."
- "We need to refactor the ORM layer to reduce coupling metrics."
- "Each new feature now takes an extra week because developers must navigate three different coding patterns."
Exercise 6: Prevention Hierarchy
Objective: Recall the three lines of defense against technical debt.
Name the three lines of defense described in Section 34.7 and provide two specific examples of tools or practices for each line.
Tier 2: Understanding and Explanation (Exercises 7-12)
Exercise 7: Explaining Style Drift
Objective: Explain why AI coding assistants produce style drift across sessions.
Write a 200-word explanation suitable for a junior developer who has never used an AI coding assistant. Address the following: - What is style drift? - Why does it happen with AI assistants but not as much with human developers? - Why is style drift harmful even when each individual file looks fine?
Exercise 8: The Financial Debt Analogy
Objective: Explain the financial debt analogy and its limitations.
The chapter uses a financial debt analogy. For each financial concept below, explain the software equivalent and give a concrete example from an AI-generated codebase:
- Principal
- Interest
- Minimum payment
- Debt consolidation
- Bankruptcy
Then identify one way the analogy breaks down — where does the comparison between financial debt and technical debt stop being accurate?
Exercise 9: Over-Engineering vs. Under-Engineering
Objective: Explain the difference between over-engineering and under-engineering as forms of technical debt.
Review the following two code snippets and explain: - Which one is over-engineered and which is under-engineered? - What specific elements make each one problematic? - What would a "right-sized" solution look like?
Snippet A:
def get_user_name(user_id):
import sqlite3
conn = sqlite3.connect("app.db")
result = conn.execute("SELECT name FROM users WHERE id=" + str(user_id))
return result.fetchone()[0]
Snippet B:
from abc import ABC, abstractmethod
from typing import TypeVar, Generic, Protocol
T = TypeVar("T")
class DataFetcher(Protocol):
def fetch(self, query: str, params: tuple) -> list: ...
class BaseRepository(ABC, Generic[T]):
@abstractmethod
def get_connection(self) -> DataFetcher: ...
@abstractmethod
def map_row(self, row: tuple) -> T: ...
def find_by_id(self, entity_id: int) -> T:
conn = self.get_connection()
rows = conn.fetch(self._get_query(), (entity_id,))
return self.map_row(rows[0]) if rows else None
@abstractmethod
def _get_query(self) -> str: ...
class UserRepository(BaseRepository[str]):
def get_connection(self):
import sqlite3
return sqlite3.connect("app.db")
def map_row(self, row):
return row[0]
def _get_query(self):
return "SELECT name FROM users WHERE id = ?"
Exercise 10: Debt Accumulation Scenario
Objective: Trace how technical debt accumulates across multiple AI sessions.
Consider a developer building a blog platform with an AI assistant across five sessions: - Session 1: User registration and authentication - Session 2: Blog post creation and editing - Session 3: Comment system - Session 4: Search functionality - Session 5: Admin dashboard
For each session, describe one plausible debt item that could be introduced and explain how it might interact with or compound debt from earlier sessions. Your answer should demonstrate the cumulative nature of AI-generated debt.
Exercise 11: Metric Interpretation
Objective: Interpret technical debt metrics and draw conclusions.
A team provides the following metrics for their AI-generated project over four months:
| Month | Avg. Complexity | Duplication % | Pattern Consistency | Test Coverage |
|---|---|---|---|---|
| Jan | 8.2 | 3.1% | 91% | 82% |
| Feb | 9.7 | 4.8% | 84% | 78% |
| Mar | 12.1 | 7.2% | 76% | 71% |
| Apr | 14.3 | 9.5% | 68% | 65% |
Answer the following: 1. What is the overall trend? 2. Which metric is deteriorating fastest? 3. What would you recommend as the highest-priority action? 4. If the team continues this trajectory for two more months, what problems are likely to emerge?
Exercise 12: AI-Specific vs. Traditional Debt
Objective: Distinguish between debt patterns unique to AI and those common to all development.
For each debt item below, classify it as "AI-specific," "traditional," or "amplified by AI" (present in traditional development but made worse by AI assistance). Justify your classification.
- Inconsistent error handling across modules
- Unused dependency imported because the AI suggested it
- Missing input validation on a rarely-used endpoint
- Three different date formatting utilities in different modules
- A function with cyclomatic complexity of 25
- A custom middleware pattern that does not match any framework convention
- Hard-coded database credentials in a config file
- Overly abstract class hierarchy for a simple CRUD operation
Tier 3: Application and Implementation (Exercises 13-18)
Exercise 13: Build a Debt Catalog
Objective: Create a structured debt catalog for a sample project.
You are reviewing a small e-commerce application. During your review, you find the following issues:
- The product module uses SQLAlchemy ORM; the order module uses raw SQL queries.
- Email validation is implemented in three places with different regex patterns.
- The payment processing module catches bare
Exceptionin seven places. - A configuration loader uses five design patterns for reading a single YAML file.
- The test suite has 45% coverage for the cart module but 90% for user auth.
- Two unused dependencies (arrow, pendulum) are in requirements.txt.
- The admin module uses camelCase while everything else uses snake_case.
Create a complete debt catalog with columns for: ID, Title, Category (from the seven AI patterns), Location, Severity (High/Medium/Low), Effort (hours or days), Risk, and Recommended Action.
Exercise 14: Write a Conventions Document
Objective: Create a project conventions document that could be shared with an AI assistant.
Write a conventions document for a Python REST API project. Include specific guidelines for: - Database access patterns - Error handling approach - Naming conventions - API response format - Logging standards - Testing patterns
The document should be concrete enough that an AI assistant following it would produce consistent code across sessions.
Exercise 15: Prioritization Exercise
Objective: Apply the effort-impact matrix to prioritize debt items.
Using the debt catalog you created in Exercise 13 (or the one provided in the solutions), assign each item an effort score (1-5, where 5 is highest effort) and an impact score (1-5, where 5 is highest impact). Plot them on the effort-impact matrix and determine:
- Which items are Quick Wins?
- Which items are Major Projects?
- Which items should be accepted (Not Worth It)?
- What order would you address the Quick Wins in?
Exercise 16: Debt Remediation Prompt Engineering
Objective: Write effective prompts for AI-assisted debt remediation.
For each of the following debt scenarios, write a complete prompt that you would give to an AI assistant to remediate the debt. Each prompt should include context, the target state, specific instructions, and any constraints.
- Three modules use different database access patterns; you want them all to use the repository pattern.
- A module has cyclomatic complexity of 28 and needs to be simplified.
- Five functions across the codebase implement slightly different versions of input sanitization.
Exercise 17: Stakeholder Report
Objective: Write a debt report suitable for non-technical stakeholders.
Using the following raw data, write a one-page debt report for a product manager:
- Total debt items: 34 (up from 28 last quarter)
- Items resolved this quarter: 8
- New items identified: 14
- Average feature delivery time: increased from 3 days to 4.5 days
- Bug rate: 2.1 per sprint (up from 1.4)
- Two modules have security-related debt items
- Test coverage: dropped from 78% to 71%
Your report should use business language, include specific recommendations, and avoid technical jargon.
Exercise 18: CI/CD Debt Gates
Objective: Design automated debt detection for a CI/CD pipeline.
Design a set of CI/CD pipeline checks that would prevent or detect technical debt in an AI-generated Python project. For each check, specify:
- What the check does
- What tool or command runs it
- What the threshold or pass/fail criteria is
- What happens when the check fails (block merge, warn, or log)
Include at least six checks covering complexity, duplication, style consistency, test coverage, dependency health, and security.
Tier 4: Analysis and Evaluation (Exercises 19-24)
Exercise 19: Comparative Analysis of Debt Strategies
Objective: Evaluate different approaches to debt management.
Compare and contrast the following three debt management strategies. For each, identify strengths, weaknesses, and the type of project it is best suited for:
- The Debt Budget: Allocate 20% of each sprint to debt reduction.
- The Cleanup Sprint: Dedicate every fourth sprint entirely to debt work.
- The Boy Scout Rule Only: No dedicated debt time; rely on incidental improvements.
Under what circumstances would each strategy fail? Which would you recommend for a three-person team working on an AI-generated project with 15,000 lines of code?
Exercise 20: Root Cause Analysis
Objective: Analyze the root causes of technical debt in a specific scenario.
A team of four developers has been using AI assistants for six months. Their codebase has grown to 40,000 lines. They report the following symptoms:
- New features take 3x longer than they did three months ago
- Every bug fix seems to introduce a new bug
- Two developers refuse to work on certain modules because "nobody understands them"
- The test suite takes 45 minutes to run and has a 15% flaky test rate
Perform a root cause analysis. For each symptom, identify at least two possible underlying debt patterns, explain the causal chain from debt to symptom, and suggest diagnostic steps to confirm each hypothesis.
Exercise 21: Debt Decision Evaluation
Objective: Evaluate debt trade-offs in realistic scenarios.
For each scenario, argue both sides (accept the debt vs. fix it now) and then make a final recommendation with justification:
- Your startup has a demo for investors in two weeks. The AI-generated authentication module works but uses three different error handling patterns.
- Your team has just discovered that the AI generated a custom caching layer instead of using Redis, which is already in your stack. The custom cache works fine but has no monitoring or eviction policies.
- A module has 0% test coverage but has worked without bugs for six months. Adding tests would take three days.
Exercise 22: Metrics Design
Objective: Design custom metrics for AI-specific debt.
The standard metrics (cyclomatic complexity, duplication percentage, etc.) do not capture all forms of AI-specific debt. Design three custom metrics that would help detect:
- Style drift across sessions
- Hallucinated patterns (patterns that do not match any standard framework convention)
- Over-engineering relative to project complexity
For each metric, define: what it measures, how to calculate it (algorithm or heuristic), what thresholds indicate a problem, and how to automate the measurement.
Exercise 23: Architecture Evolution
Objective: Plan an architectural evolution for a debt-laden codebase.
An AI-generated e-commerce application has the following architecture problems: - The "models" directory contains 47 files, many with overlapping responsibilities - Three different ORMs are used across the codebase - Business logic is scattered between route handlers, service classes, and model methods - There is no dependency injection; all dependencies are hard-coded
Design a three-phase evolution plan to address these issues. For each phase: - What specific changes will be made? - What is the expected timeline? - What risks exist? - How will you measure success? - How will you use AI assistants to help with the migration?
Exercise 24: Team Process Design
Objective: Design a team process for ongoing debt management.
You are the tech lead for a team of five developers, all using AI assistants. Design a complete debt management process that includes:
- How debt is identified (both automated and manual)
- How debt is cataloged and tracked
- How debt is prioritized
- How remediation time is allocated
- How progress is communicated to stakeholders
- What metrics are tracked and how often
- What training or guidance developers receive about debt prevention
Your process should be practical for a team that ships features weekly and cannot dedicate more than 15% of their time to debt work.
Tier 5: Synthesis and Creation (Exercises 25-30)
Exercise 25: Build a Pattern Consistency Checker
Objective: Create a tool that detects pattern inconsistencies across modules.
Write a Python script that: 1. Scans a directory of Python files 2. Identifies the database access pattern used in each file (raw SQL, ORM query builder, ORM model methods) 3. Identifies the error handling pattern used (bare except, specific exceptions, no error handling) 4. Generates a consistency report showing which files deviate from the dominant patterns
The script should produce output like:
Pattern Consistency Report
==========================
Database Access:
Dominant pattern: ORM model methods (7/10 files)
Deviations:
- orders/repository.py: raw SQL
- reports/queries.py: raw SQL
- legacy/data.py: ORM query builder
Error Handling:
Dominant pattern: specific exceptions (6/10 files)
Deviations:
- payments/processor.py: bare except (3 instances)
- legacy/data.py: no error handling
...
Exercise 26: Debt Impact Simulator
Objective: Build a simulation that demonstrates how technical debt affects development velocity over time.
Create a Python program that simulates a development team working on a project over 12 months. The simulation should: - Model feature development (each feature adds code and potentially adds debt) - Model debt accumulation (each AI session has a probability of adding debt) - Model the "interest" effect (more debt = slower development) - Model debt remediation (time spent fixing debt reduces total debt) - Compare three strategies: no debt management, 10% debt budget, and 20% debt budget
Output the simulation results as a summary showing velocity, total debt, and features completed for each strategy.
Exercise 27: Automated Debt Report Generator
Objective: Create a tool that generates stakeholder-friendly debt reports.
Write a Python program that: 1. Takes a debt catalog (as a JSON or CSV file) as input 2. Calculates summary statistics (total items, breakdown by severity, new vs. resolved) 3. Generates a formatted report in Markdown suitable for non-technical stakeholders 4. Includes trend analysis (if historical data is available) 5. Highlights the top 5 items by priority score
The output should use business language, avoid technical jargon, and include specific recommendations.
Exercise 28: Convention Enforcement Tool
Objective: Build a tool that checks code against project conventions.
Create a Python script that reads a conventions configuration file (YAML or JSON) and checks Python source files against those conventions. The tool should check for:
- Naming convention compliance (function names, class names, variable names)
- Required imports (e.g., all modules must import the project logger)
- Prohibited patterns (e.g., no bare
except:, noimport *) - Required patterns (e.g., all functions must have docstrings, all functions must have type hints)
The tool should produce a report listing violations with file names and line numbers.
Exercise 29: End-to-End Debt Management System
Objective: Combine scanning, tracking, and reporting into a complete system.
Using the code examples from this chapter as a foundation, build a complete debt management system that:
- Scans a codebase for common debt patterns (using and extending example-01)
- Tracks identified debt items with metadata (using and extending example-02)
- Measures code quality metrics (using and extending example-03)
- Prioritizes items using the effort-impact framework
- Generates a stakeholder report
The system should work as a CLI tool that can be run against any Python project directory.
Exercise 30: Debt Prevention Framework
Objective: Design and implement a comprehensive debt prevention framework.
Create a complete debt prevention framework for an AI-assisted Python project that includes:
- A project conventions document (Markdown)
- A pre-commit hook script that checks for common debt patterns
- A PR review checklist template
- An AI system prompt that incorporates the conventions
- A monthly debt review process document
Implement the pre-commit hook as a working Python script and provide the other documents as templates. The framework should be practical enough to adopt in a real project today.