One problem. Many right answers.
“Is this good code?” is the wrong question, and here is why, in code you can read. Below is one small problem solved five ways. Each solution is written for a different purpose, and Facet profiles each across the same 14 dimensions. Watch what happens: no solution is best on every axis. Each wins the dimensions its purpose cares about and deliberately trades the rest.
The problem — Total amount per account
Given a stream of transactions — each a (account_id, amount, timestamp) — return the total amount for each account_id. Small, real, and solvable many ways. Below are five solutions to the SAME problem, each written for a different purpose. Facet profiles each one; notice that none is best on every axis — each wins the dimensions its purpose cares about and trades away the ones it doesn't.
P2 Throwaway script
pythonGet a one-off job done fast: five lines, no ceremony, no guards.
import csv, sys
t = {}
for r in csv.reader(open(sys.argv[1])):
t[r[0]] = t.get(r[0], 0) + float(r[1])
print(t)
Facet reads this as P2 THROWAWAY SCRIPT · runner-up P8 RESEARCH PROTOTYPE
13 reliable · 0 provisional
P1 Hot path
pythonThroughput first: single pass, integer cents, no per-row allocation or validation.
"""Single-pass aggregation in integer cents, built for throughput on a hot path.
No per-row objects, no Decimal, no validation overhead: split, parse to int cents, accumulate.
Money stays exact because it never touches float.
"""
from collections import defaultdict
def total_cents_per_account(rows):
totals = defaultdict(int)
for acct, amount, _ts in rows:
neg = amount[:1] == "-"
whole, _, frac = (amount[1:] if neg else amount).partition(".")
cents = int(whole) * 100 + int((frac + "00")[:2])
totals[acct] += -cents if neg else cents
return totals
Facet reads this as P1 HOT PATH · runner-up P7 HIGH-CONCURRENCY SERVICE
14 reliable · 0 provisional
P4 Regulated core
pythonCorrectness and traceability: exact decimals, validation, audit logging, a reconciliation invariant.
"""Decimal-exact ledger aggregation with schema validation, audit logging, and a reconciliation
invariant. Built for a regulated core where correctness and traceability outrank speed."""
from __future__ import annotations
import logging
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import Iterable
logger = logging.getLogger("ledger.aggregate")
@dataclass(frozen=True)
class Transaction:
account_id: str
amount: Decimal
timestamp: str
class TransactionError(ValueError):
"""A row failed validation; carries enough context for the audit trail."""
def parse_row(row: list[str]) -> Transaction:
if len(row) != 3:
raise TransactionError(f"expected 3 fields, got {len(row)}")
account_id, raw_amount, timestamp = (field.strip() for field in row)
if not account_id:
raise TransactionError("missing account id")
try:
amount = Decimal(raw_amount)
except InvalidOperation as exc:
raise TransactionError(f"invalid amount {raw_amount!r}") from exc
return Transaction(account_id, amount, timestamp)
def totals_per_account(rows: Iterable[list[str]]) -> dict[str, Decimal]:
"""Sum amounts per account using exact decimal arithmetic. Invalid rows are rejected and
logged, never silently dropped, and the result is reconciled against a running grand total."""
totals: dict[str, Decimal] = {}
grand = Decimal("0")
rejected = 0
for row in rows:
try:
tx = parse_row(row)
except TransactionError:
rejected += 1
logger.warning("rejected transaction row", exc_info=True)
continue
totals[tx.account_id] = totals.get(tx.account_id, Decimal("0")) + tx.amount
grand += tx.amount
if sum(totals.values(), Decimal("0")) != grand:
raise AssertionError("reconciliation failed: per-account totals do not sum to grand total")
logger.info("aggregated %d accounts (%d rows rejected)", len(totals), rejected)
return totals
Facet reads this as P5 TEACHING EXAMPLE · runner-up P1 HOT PATH
14 reliable · 0 provisional
P9 Security-critical boundary
pythonAssume hostile input: bounded resources, strict allow-list parsing, reject the malformed.
"""Aggregation that treats its input as hostile: every resource is bounded and every field is
strictly validated before use. Built for a security-critical boundary facing untrusted data."""
from decimal import Decimal, InvalidOperation
MAX_ROWS = 1_000_000 # refuse unbounded input (DoS bound)
MAX_FIELD_LEN = 64 # bound per-field length (memory + log-injection guard)
MAX_ACCOUNTS = 100_000 # bound distinct-account cardinality
def aggregate(rows):
totals: dict[str, Decimal] = {}
for i, row in enumerate(rows):
if i >= MAX_ROWS:
raise ValueError("row limit exceeded")
if len(row) != 3:
raise ValueError("malformed row: wrong field count")
account_id, raw_amount, _timestamp = row
if len(account_id) > MAX_FIELD_LEN or len(raw_amount) > MAX_FIELD_LEN:
raise ValueError("field exceeds maximum length")
if not account_id.isalnum(): # strict allow-list, never a blocklist
raise ValueError("account id is not alphanumeric")
try:
amount = Decimal(raw_amount)
except InvalidOperation:
raise ValueError("amount is not a valid decimal")
if not amount.is_finite():
raise ValueError("amount is not finite")
if account_id not in totals and len(totals) >= MAX_ACCOUNTS:
raise ValueError("account cardinality limit exceeded")
totals[account_id] = totals.get(account_id, Decimal("0")) + amount
return totals
Facet reads this as P2 THROWAWAY SCRIPT · runner-up P5 TEACHING EXAMPLE
14 reliable · 0 provisional
P5 Teaching example
pythonOptimised for a learner: documented, simple structures, explained step by step.
"""
Summing transactions, explained.
Goal: given a list of transactions, find the total amount for each account.
A transaction is a pair (account_id, amount). We keep a running total for each
account in a dictionary, adding each amount to the matching account as we go.
"""
from collections import defaultdict
def total_per_account(transactions):
"""Return the total amount for each account.
Args:
transactions: an iterable of (account_id, amount) pairs, for example
[("alice", 10.0), ("bob", 12.5), ("alice", 20.0)]
Returns:
A dictionary mapping each account id to the sum of its amounts, for example
{"alice": 30.0, "bob": 12.5}
"""
totals = defaultdict(float)
for account_id, amount in transactions:
# defaultdict(float) starts each new account at 0.0, so we can just add.
totals[account_id] += amount
return dict(totals)
Facet reads this as P5 TEACHING EXAMPLE · runner-up P3 PUBLIC LIBRARY
14 reliable · 0 provisional
So which one is “best”?
None of them, and all of them. The throwaway is passing as a throwaway; the regulated core would be failing if you judged it as one. Judge any of these against the wrong profile and it looks broken. That is the whole idea: code quality is a profile, not a score, and writing more than one of these — knowing which trade you are making — is what range looks like.