04 Exercise: Code-to-Requirements Extraction
January 2026 (868 Words, 5 Minutes)
Introduction
Requirements are often implicit in code rather than documented. By analyzing code, we can extract the preconditions (what must be true before the function runs), postconditions (what the function guarantees), and invariants (what always remains true).
Learning Objectives:
- Extract preconditions from code validation logic
- Identify postconditions from return value constraints
- Write formal requirements based on code analysis
- Recognize implicit/undocumented requirements
Instructions:
- Study the Design by Contract reference
- Carefully read the provided Python function
- Complete all four tasks in writing
- Check your answers against the solution
Total Points: 25 Time: ~25 minutes
Reference: Design by Contract
| Term | Definition | Example |
|---|---|---|
| Precondition | A condition that must be true before a function executes | "Input must be a positive integer" |
| Postcondition | A condition the function guarantees after execution | "Return value is always between 0 and 1" |
| Invariant | A condition that remains true throughout execution | "Account balance never goes negative" |
Code to Analyze
Study the following Python function carefully. Line numbers are provided for reference.
1 def calculate_discount(
2 customer_type: str,
3 order_amount: float,
4 is_member: bool
5 ) -> float:
6 """Calculate discount percentage for an order."""
7
8 if customer_type not in ["regular", "premium", "vip"]:
9 raise ValueError("Invalid customer type")
10
11 if order_amount < 0:
12 raise ValueError("Order amount cannot be negative")
13
14 if order_amount > 100000:
15 raise ValueError("Order amount exceeds maximum")
16
17 base_discount = 0.0
18
19 if customer_type == "premium":
20 base_discount = 0.10
21 elif customer_type == "vip":
22 base_discount = 0.20
23
24 if is_member and order_amount >= 100:
25 base_discount += 0.05
26
27 if order_amount >= 500:
28 base_discount += 0.03
29
30 # Cap discount at 25%
31 return min(base_discount, 0.25)
Task A: Extract Preconditions (8 points)
List 4 preconditions that must be true for this function to execute successfully (without raising an exception).
Reference the line numbers where you found each precondition.
Your Answer:
| # | Precondition | Line(s) |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
(2 points per precondition)
Task B: Document Postconditions (6 points)
List 2 postconditions - guarantees about what the function returns when preconditions are met.
Your Answer:
| # | Postcondition | Line(s) |
|---|---|---|
| 1 | ||
| 2 |
(3 points per postcondition)
Task C: Write Formal Requirements (9 points)
Based on the code, write 3 formal requirements using proper requirement IDs.
Use this format:
REQ-DISC-001: The system shall [action] when [condition].
Your Answer:
REQ-DISC-001:
REQ-DISC-002:
REQ-DISC-003:
(3 points per requirement)
Task D: Identify Implicit Requirement (2 points)
Identify 1 requirement that is implied by the business logic but is NOT explicitly validated or documented in the code.
Hint: Think about what assumptions the code makes that could be requirements.
Your Answer:
Solution
Show Solution
Task A: Preconditions
| # | Precondition | Line(s) |
|---|---|---|
| 1 | customer_type must be one of: "regular", "premium", or "vip" |
8-9 |
| 2 | order_amount must be >= 0 (non-negative) |
11-12 |
| 3 | order_amount must be <= 100,000 |
14-15 |
| 4 | is_member must be a boolean value |
2-4 (type hint) |
Alternative acceptable answers:
customer_typemust be a string (line 2)order_amountmust be a float/number (line 3)
Task B: Postconditions
| # | Postcondition | Line(s) |
|---|---|---|
| 1 | Return value is always between 0.0 and 0.25 (inclusive) | 17, 30-31 |
| 2 | Return value is a float representing a discount percentage | 5, 31 |
Alternative acceptable answers:
- Return value is never greater than 0.25 (line 31)
- Function always returns (never raises) when preconditions are met
- Return value is non-negative (base starts at 0.0, only additions)
Task C: Formal Requirements
REQ-DISC-001: The system shall apply a 10% base discount when the customer type is “premium”.
REQ-DISC-002: The system shall apply an additional 5% discount when the customer is a member AND the order amount is at least $100.
REQ-DISC-003: The system shall cap the total discount at 25% regardless of accumulated discounts.
Alternative acceptable requirements:
- REQ-DISC-004: The system shall apply a 20% base discount for VIP customers.
- REQ-DISC-005: The system shall apply an additional 3% discount for orders of $500 or more.
- REQ-DISC-006: The system shall reject orders exceeding $100,000.
- REQ-DISC-007: The system shall reject negative order amounts.
Task D: Implicit Requirements
Acceptable answers include:
-
Currency assumption: The code assumes all amounts are in the same currency (no currency conversion).
-
No membership tier interaction: The code assumes membership bonus (5%) applies equally to all customer types - there’s no documented rule about whether VIPs who are also members should get the bonus.
-
Order amount precision: The code doesn’t specify decimal precision for order amounts or returned discounts.
-
Concurrent discount rules: The code doesn’t document whether these discounts can stack with promotional codes or other discount systems.
-
Audit/logging: There’s no requirement for logging discount calculations for auditing purposes.
-
Rounding behavior: No explicit requirement for how discount percentages should be applied/rounded when calculating final prices.
Grading Notes
-
Task A: Award 2 points for each correctly identified precondition with correct line reference. Award 1 point if precondition is correct but line reference is wrong.
-
Task B: Award 3 points for clear, correct postconditions. Award 2 points for partially correct (e.g., “returns a number” without specifying range).
- Task C: Award 3 points for requirements that:
- Use correct format (REQ-ID: The system shall…)
- Are testable
- Accurately reflect code behavior
Award 2 points if format is wrong but content is correct. Award 1 point for vague requirements.
- Task D: Award 2 points for any reasonable implicit requirement not visible in the code. Award 1 point for implicit requirements that are partially covered.