Design a Pluggable Payroll Cost Estimator
Data Structure DesignModel answerLast updated
Design the types and API that compute an employee's full cost from salary, tax, benefits, and a signed location adjustment, with exact money math, explicit missing-rule handling, and versioned rules.
You are asked to design the classes and the calculation entry point for a service that reports what an employee costs the business. The total is the sum of four parts:
- Salary: the base pay stored on the employee record.
- Tax: a single flat percentage applied to the base salary.
- Benefits: an amount found in a table indexed by the pair
(level, title). - Location adjustment: an amount found in a table indexed by location. It may be positive (a premium) or negative (a discount).
Describe the types you would define and how the calculation works. Your answer should cover:
- Input validation.
- How money is represented and rounded.
- What happens when a benefits or location entry is missing.
- How rule data is versioned.
- How you would test the design.
The design should be easy to extend (for example, adding a fifth cost component later) and should not rely on a long chain of hard-coded conditionals.
Assumptions
- Every calculation uses one declared currency.
- The tax rate and both lookup tables are supplied as configuration. They are not constants buried inside the employee class.
- Level, title, and location are given as canonical identifiers, not free text.
- Re-running a calculation after the rules change must still be able to reproduce the original result.
Questions worth raising with the interviewer
- Can the tax rate depend on the employee or location, or is it truly one flat rate?
- Should a missing rule raise an error, count as zero, or fall back to a more general rule?
- Are location adjustments fixed amounts or percentages, and are they annual?
- What rounding mode and currency precision apply?
Hints
Hint 1
Split the problem into data (employee), rules (rates and lookup tables), and output (a result object). The employee should not know how cost is computed.
Hint 2
Think of each cost part as a small component that takes the employee and a rules snapshot and returns a named, signed money amount. The total is the sum of the components, so adding a new part does not touch existing ones.
Hint 3
Avoid floats. Use a decimal type or integer minor units, define one rounding point, and decide up front whether a missing lookup is an error, a zero, or a fallback. Stamp each result with the rules version it used.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
I would confirm four things before designing, and state my defaults if the interviewer has no preference:
- Tax: one flat percentage of base salary. I would still model it as a rule object so a per-location rate can be added later.
- Adjustment: an annual fixed amount, signed. If it is a percentage, that is a different component class, not a flag.
- Missing rules: fail loudly by default (see below).
- Rounding: the currency's minor unit, using half-even or half-up, applied at a single defined point.
Types
@dataclass(frozen=True)
class Money:
minor: int # integer minor units (cents)
currency: str
@dataclass(frozen=True)
class Employee:
id: str
level: str # canonical id, e.g. "L5"
title: str # canonical id, e.g. "SWE"
location: str # canonical id, e.g. "US-NYC"
base_salary: Money
@dataclass(frozen=True)
class RuleSet:
version: str
currency: str
tax_rate: Decimal # e.g. Decimal("0.20")
benefits: Mapping[tuple[str, str], Money] # (level, title) -> amount
location_adj: Mapping[str, Money] # may be negative
@dataclass(frozen=True)
class CostLine:
name: str
amount: Money
@dataclass(frozen=True)
class CostBreakdown:
employee_id: str
rules_version: str
lines: tuple[CostLine, ...]
total: Money
Each component implements one interface:
class CostComponent(Protocol):
name: str
def compute(self, emp: Employee, rules: RuleSet) -> Money: ...
Concrete components: SalaryComponent, TaxComponent, BenefitsComponent, LocationAdjustmentComponent.
class CostCalculator:
def __init__(self, components: Sequence[CostComponent]):
self.components = components
def calculate(self, emp: Employee, rules: RuleSet) -> CostBreakdown:
validate(emp, rules)
lines = tuple(CostLine(c.name, c.compute(emp, rules)) for c in self.components)
total = sum_money(l.amount for l in lines)
return CostBreakdown(emp.id, rules.version, lines, total)
Adding a fifth component (say, equipment cost) means writing one class and registering it. The calculator and the existing components do not change. That is the extensibility the problem asks for.
Money
- Never use binary floating point.
0.1 + 0.2 != 0.3errors accumulate across thousands of employees. - Store integer minor units, or use a decimal type, together with a currency code.
Moneyoperations refuse to mix currencies; a mismatch is a programming error and raises.- Only tax involves multiplication by a fraction:
tax = round(base * rate). Round once, at that point, with a documented mode. Everything else is already in minor units, so addition is exact. - Negative amounts are valid. Do not use an unsigned type or reject negatives for the location adjustment. Do reject a negative base salary.
- The total may be validated or flagged if it drops below zero, but that is a business decision to confirm.
Example: base 100,000.00, tax 20%, benefits 12,000.00, location adjustment -5,000.00 gives 100,000 + 20,000 + 12,000 - 5,000 = 127,000.00.
Validation
At the boundary, before any calculation:
- Salary is non-negative and in the rule set's currency.
- Tax rate is within an agreed range, such as 0 to 1.
- Identifiers are canonical: normalize or reject (case, whitespace, aliases) in one place, not inside each lookup. A composite key
(level, title)should be built from already-canonical parts, so("L5","SWE")and("l5 ","swe")cannot become different entries. - Rule tables are validated at load time (no duplicate keys, same currency everywhere), so a bad file fails at deploy, not mid-calculation.
Missing lookups
Silent defaults to zero are the most dangerous option, because a gap in the table quietly under-reports cost. My default:
- Fail explicitly with a typed error such as
MissingRuleError(kind="benefits", key=("L5","SWE"), version="2024-07"). - If the business wants fallbacks, make them an explicit, documented hierarchy (exact
(level, title)→ level default → error) and record in the breakdown line which rule matched. - If "no adjustment" is legitimate for some locations, store an explicit zero entry rather than treating absence as zero.
Distinguishing "rule says zero" from "rule is missing" is a common point where designs go wrong.
Versioning and reproducibility
- Treat a
RuleSetas an immutable, versioned snapshot (an id or effective date). Never mutate it in place. - Pass the snapshot into
calculate; do not read globals. This also makes the calculator a pure function, which makes it trivial to test and cache. - Store the
rules_versionon everyCostBreakdown. To reproduce an old result, load that version and the employee's data as of that date. If employee records change, either snapshot the inputs or keep effective-dated history. - Keep the breakdown lines: auditors and finance will ask why a total changed, and a per-component diff answers that.
Trade-offs
- Component objects add a few classes compared with one function, but they remove the conditional chain and keep each rule independently testable.
- Integer minor units are exact and fast but need care for fractional rates; decimals are friendlier but need a fixed context. Either is fine if rounding is centralized.
- Strict failure on missing rules is safer but can block reports during a data rollout; a fallback hierarchy trades some strictness for availability, as long as it is visible in the output.
Tests
- Happy path: the worked example above, checking each line and the total.
- Negative adjustment: the total decreases; also an adjustment larger than the salary-plus-other-parts, to exercise the negative-total policy.
- Zero cases: zero salary; zero tax rate; explicit zero benefits.
- Boundaries: tax rate 0 and 1; very large salaries; amounts that force rounding (for example 33,333.33 at 7.25%), including a half-way case to verify the rounding mode.
- Missing rules: absent benefits key, absent location, each raising the specific error; fallback behavior if implemented.
- Canonicalization: non-canonical identifiers are normalized or rejected consistently.
- Currency: mismatched currency raises.
- Reproducibility: the same employee under two rule versions gives different totals, and re-running with the old version gives the old result exactly.
- Extensibility: register a dummy component and confirm it appears in the breakdown and total without changing other code.
- Property test: total always equals the sum of lines.
Common mistakes
- Using
floatordoublefor money. - Rounding at several intermediate steps, producing off-by-a-cent totals.
- Treating a missing lookup as zero.
- Keying the benefits table by unnormalized strings or by concatenated text like
"L5SWE", which risks collisions. - Hiding the tax rate or tables in static fields, which breaks versioning and tests.
- Returning only a total, so nobody can explain it later.