Build a Fee Calculator with Comprehensive Test Coverage
Data Structure DesignModel answerLast updated
Write a service class that computes fees based on business rules, then extend it and write unit tests covering normal cases, boundaries, and errors.
You need to build a fee calculation service from scratch. You'll receive a written specification describing the pricing rules. Your task has three components:
- Implement the core pricing logic using straightforward conditional statements and thorough input validation
- Extend the implementation with an additional feature after clarifying requirements
- Write comprehensive unit tests that verify correct behavior for typical inputs, boundary conditions, and invalid input handling
The service should be a standalone class with no external dependencies. State all assumptions explicitly before coding. Provide clear method signatures and demonstrate your testing approach with representative test cases.
Example specification (your interviewer will provide the actual spec):
Create a ShippingCostService class with a method compute_cost(weight_oz, zone) that returns cost in cents:
- Base cost is 399 cents
- Packages under 16 oz are free to ship
- Each ounce from 16 oz onward adds 25 cents (round partial ounces up)
- Zone must be 1-8; weight must be 0-128 oz
- Invalid inputs should raise appropriate exceptions
Extension: Add an optional is_premium parameter. Premium members with packages over 32 oz pay half the per-ounce rate.
Your solution should demonstrate proper type checking, range validation, backward compatibility when extending, and comprehensive test coverage.
Hints
Hint 1
Validate all inputs before performing any calculations—fail fast with clear error messages
Hint 2
Use named constants for all business values so pricing rules can be updated in one place
Hint 3
When extending functionality, use keyword-only arguments with defaults to maintain backward compatibility
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to translate business requirements into clean, testable code. Strong candidates structure their solution in three clear layers: validation, business logic, and comprehensive testing.
Step 1: Clarify Requirements
Before writing code, state your assumptions explicitly:
- Data types: Money values are integers (cents) to avoid floating-point errors. Weight can be a decimal number.
- Rounding rules: "Round up" means any fraction increments the count (ceiling function).
- Validation policy: Never silently clamp or coerce invalid inputs. Raise typed exceptions (
TypeErrorfor wrong types,ValueErrorfor out-of-range values). - Edge cases: Confirm behavior at exact thresholds (16.0 oz, 32.0 oz) and boundaries (zone 1 vs 9, weight 0 vs 129).
- Extension compatibility: New parameters must not break existing callers.
Step 2: Structure the Implementation
Break the solution into modular pieces:
Validation Layer:
- Check types first (reject
boolmasquerading asintin Python) - Check ranges next
- Reject special float values (
NaN,inf) explicitly - Fail fast—validate everything before computing anything
Business Logic Layer:
- Extract each fee component into a separate calculation
- Use named constants for all magic numbers
- Apply conditional waivers or adjustments before combining components
- Keep branching logic simple and flat
Testing Layer:
- Organize tests by feature and scenario type
- Use parameterized tests to avoid repetition
- Cover: happy paths, exact boundaries, one step on each side of boundaries, type errors, range errors
- Verify backward compatibility explicitly when extending
Step 3: Implementation Pattern
import math
from numbers import Real
class ShippingCostService:
# All business rules as constants
BASE_COST_CENTS = 399
FREE_WEIGHT_OZ = 16
PER_OZ_CENTS = 25
MIN_ZONE = 1
MAX_ZONE = 8
MAX_WEIGHT_OZ = 128
PREMIUM_THRESHOLD_OZ = 32
def compute_cost(self, weight_oz: float, zone: int,
*, is_premium: bool = False) -> int:
"""Calculate shipping cost in cents."""
self._validate_inputs(weight_oz, zone, is_premium)
# Extension: premium discount applies above threshold
if is_premium and weight_oz > self.PREMIUM_THRESHOLD_OZ:
per_oz_rate = self.PER_OZ_CENTS // 2
else:
per_oz_rate = self.PER_OZ_CENTS
if weight_oz <= self.FREE_WEIGHT_OZ:
weight_charge = 0
else:
billable_oz = math.ceil(weight_oz - self.FREE_WEIGHT_OZ)
weight_charge = billable_oz * per_oz_rate
return self.BASE_COST_CENTS + weight_charge
def _validate_inputs(self, weight_oz, zone, is_premium) -> None:
# Reject bool as int (Python quirk)
if isinstance(weight_oz, bool) or not isinstance(weight_oz, Real):
raise TypeError("weight_oz must be numeric")
if not math.isfinite(weight_oz):
raise ValueError("weight_oz must be finite")
if weight_oz < 0 or weight_oz > self.MAX_WEIGHT_OZ:
raise ValueError(f"weight_oz must be 0-{self.MAX_WEIGHT_OZ}")
if isinstance(zone, bool) or not isinstance(zone, int):
raise TypeError("zone must be int")
if zone < self.MIN_ZONE or zone > self.MAX_ZONE:
raise ValueError(f"zone must be {self.MIN_ZONE}-{self.MAX_ZONE}")
if not isinstance(is_premium, bool):
raise TypeError("is_premium must be bool")
Step 4: Comprehensive Testing
import unittest
class TestShippingCostService(unittest.TestCase):
def setUp(self):
self.service = ShippingCostService()
def test_base_cases(self):
"""Verify core pricing logic."""
cases = [
# (weight, zone, premium, expected)
(0, 1, False, 399), # minimum weight
(15.9, 1, False, 399), # just under free threshold
(16.0, 1, False, 399), # exact threshold
(16.1, 1, False, 424), # rounds up to 1 oz
(32, 1, False, 799), # 16 billable oz
(128, 1, False, 3199), # max weight
]
for weight, zone, premium, expected in cases:
with self.subTest(weight=weight, premium=premium):
result = self.service.compute_cost(weight, zone,
is_premium=premium)
self.assertEqual(result, expected)
def test_premium_discount(self):
"""Premium members get half-rate above 32 oz."""
# Below threshold: no discount
self.assertEqual(
self.service.compute_cost(32, 1, is_premium=True), 799)
# Above threshold: half rate on all billable weight
# 33 oz = 17 billable, at 12.5¢ each = 212.5 → 213 cents
self.assertEqual(
self.service.compute_cost(33, 1, is_premium=True), 612)
def test_backward_compatibility(self):
"""Extension doesn't break existing callers."""
# Old call style still works
result = self.service.compute_cost(20, 5)
self.assertEqual(result, 499)
def test_invalid_types(self):
"""Wrong types raise TypeError."""
with self.assertRaises(TypeError):
self.service.compute_cost("20", 1)
with self.assertRaises(TypeError):
self.service.compute_cost(20, 1.5)
with self.assertRaises(TypeError):
self.service.compute_cost(20, 1, is_premium="yes")
def test_invalid_ranges(self):
"""Out-of-range values raise ValueError."""
with self.assertRaises(ValueError):
self.service.compute_cost(-1, 1)
with self.assertRaises(ValueError):
self.service.compute_cost(129, 1)
with self.assertRaises(ValueError):
self.service.compute_cost(20, 0)
with self.assertRaises(ValueError):
self.service.compute_cost(20, 9)
with self.assertRaises(ValueError):
self.service.compute_cost(float('nan'), 1)
Complexity
- Time: O(1) — fixed number of comparisons and arithmetic operations
- Space: O(1) — only primitive values stored
Common Mistakes
- Silent failures: Clamping invalid inputs instead of raising exceptions loses critical debugging information
- Float for money: Using floating-point for currency creates rounding errors; always use integer cents
- Implicit bool-to-int: Python treats
Trueas 1; explicit type checking prevents this - Breaking changes: Adding required parameters breaks all existing callers; use keyword-only defaults
- Incomplete validation: Forgetting to check for
NaNorinfallows nonsensical values through - Testing only happy paths: Boundary and error cases reveal most bugs
Key Takeaways
Strong implementations separate concerns cleanly: validate once at the entry point, compute with confidence on clean data, and test exhaustively. Use constants for all business values to make changes safe and obvious. When extending, preserve backward compatibility and verify it with dedicated tests.