Sign in

Specifying and verifying functional requirements in software systems

Learn how to define, translate, and verify functional requirements as executable constraints and stateful system behaviors.

MonksBit Desk

November 18, 2026 · 8 min read · 83 views

Read

A functional requirement specifies a distinct, observable behavior or calculation that a software system must execute in response to specific inputs or state conditions. It defines what transformation the software must perform rather than the runtime constraints under which it runs.

You will need. Basic familiarity with Python data structures and functions · Understanding of conditional branching and basic error handling

How well do you know this already?

The full lesson

Level 1 · Beginner: Translating natural language statements into deterministic rules

Every software component exists to solve a concrete task. A functional requirement defines the precise input-to-output mapping for that task. For instance, consider a user balance transfer requirement: Given sender account S, receiver account R, and amount A, deduct A from S and credit A to R if and only if S has at least balance A, where A is positive.

To convert this statement into an algorithm, trace the requirement step by step with concrete values. Suppose sender Alice has 100 dollars and receiver Bob has 50 dollars. If Alice requests to send 30 dollars, check if 30 is positive. It is. Check if Alice has at least 30. 100 is greater than or equal to 30. Deduct 30 from Alice, leaving 70, and add 30 to Bob, yielding 80.

If the input violates any condition, such as Alice attempting to send 120 dollars or negative 10 dollars, the requirement mandates that the operation aborts without modifying either balance. The algorithm reflects these exact guards before applying any mutations.

A minimal transfer function satisfying explicit debit and credit rules

def transfer_funds(accounts: dict[str, int], sender: str, recipient: str, amount: int) -> bool:    if amount <= 0:        return False    if sender not in accounts or recipient not in accounts:        return False    if accounts[sender] < amount:        return False    accounts[sender] -= amount    accounts[recipient] += amount    return Trueledger = {"Alice": 100, "Bob": 50}success = transfer_funds(ledger, "Alice", "Bob", 30)assert success is Trueassert ledger == {"Alice": 70, "Bob": 80}

Key takeaways

  • Functional requirements describe inputs, outputs, and conditional behavior.
  • Input validation must precede state updates to prevent partial execution.
  • Every requirement path must yield a deterministic outcome.

Level 2 · Intermediate: Enforcing state transitions and domain invariances

Real-world functional requirements rarely operate in isolation. They form state machines where past actions dictate the validity of current operations. A complete requirement specification must account for missing entities, state invariants, and atomic updates where either all state updates persist or none do.

Consider an order processing system. The functional requirements state: 1. An order can transition from PENDING to PAID only when payment confirmation is supplied. 2. A PAID order can be CANCELLED only if it has not yet transitioned to SHIPPED. 3. Cancelling a PAID order must trigger an inventory restock event.

Implementing these requirements involves verifying precondition assertions, capturing transitions cleanly, and guarding against duplicate operations or invalid sequences. Automated tests must execute both valid transitions and every forbidden branch.

Order lifecycle state transition manager with invariant validation

from enum import Enumfrom dataclasses import dataclassclass OrderState(Enum):    PENDING = "PENDING"    PAID = "PAID"    SHIPPED = "SHIPPED"    CANCELLED = "CANCELLED"@dataclassclass Order:    order_id: str    items: dict[str, int]    state: OrderState = OrderState.PENDINGclass OrderManager:    def __init__(self, inventory: dict[str, int]):        self.inventory = inventory        self.orders: dict[str, Order] = {}    def create_order(self, order_id: str, items: dict[str, int]) -> Order:        if order_id in self.orders:            raise ValueError("Order already exists")        for item, qty in items.items():            if qty <= 0:                raise ValueError("Quantity must be positive")            if self.inventory.get(item, 0) < qty:                raise ValueError(f"Insufficient stock for {item}")        for item, qty in items.items():            self.inventory[item] -= qty        order = Order(order_id=order_id, items=items)        self.orders[order_id] = order        return order    def pay_order(self, order_id: str) -> None:        order = self.orders.get(order_id)        if not order:            raise KeyError("Order not found")        if order.state != OrderState.PENDING:            raise ValueError(f"Cannot pay for order in state {order.state}")        order.state = OrderState.PAID    def cancel_order(self, order_id: str) -> None:        order = self.orders.get(order_id)        if not order:            raise KeyError("Order not found")        if order.state not in (OrderState.PENDING, OrderState.PAID):            raise ValueError(f"Cannot cancel order in state {order.state}")        for item, qty in order.items.items():            self.inventory[item] += qty        order.state = OrderState.CANCELLED# Verification teststock = {"book": 5}manager = OrderManager(stock)ord = manager.create_order("ORD1", {"book": 2})assert stock["book"] == 3manager.pay_order("ORD1")manager.cancel_order("ORD1")assert ord.state == OrderState.CANCELLEDassert stock["book"] == 5

Key takeaways

  • State machines prevent invalid sequences of operations mandated by requirements.
  • Precondition checks guard invariants before mutating persistent records.
  • Reversal logic such as inventory replenishment must restore exact pre-operation balances.

Level 3 · Advanced: Property-based specification and formal verification rules

In distributed and safety-critical architectures, functional requirements cannot be validated solely with hand-written unit tests. Systems employ formal specification techniques, such as property-based contracts and declarative invariants, to guarantee that requirements hold across arbitrary sequences of actions.

A property is an invariant rule that must remain true across any valid input domain. For a balance system, one core invariant is value conservation: the sum of balances across all accounts and fees must equal the system initial total before and after any sequence of transfers.

Furthermore, when functional specifications require idempotency, repeating the exact same command multiple times must yield the identical state as executing it once. This is modeled mathematically by designing state transformers where f(f(x)) equals f(x).

An idempotent transaction log verifying conservation of value invariants

import uuidclass FinancialLedger:    def __init__(self):        self.accounts: dict[str, int] = {}        self.processed_tx_ids: set[str] = set()    def deposit(self, account: str, amount: int) -> None:        if amount <= 0:            raise ValueError("Deposit must be positive")        self.accounts[account] = self.accounts.get(account, 0) + amount    def transfer(self, tx_id: str, sender: str, receiver: str, amount: int) -> bool:        if tx_id in self.processed_tx_ids:            return True        if amount <= 0:            return False        if self.accounts.get(sender, 0) < amount:            return False        if receiver not in self.accounts:            return False        initial_total = sum(self.accounts.values())        self.accounts[sender] -= amount        self.accounts[receiver] += amount        self.processed_tx_ids.add(tx_id)                # Invariant assertion verifying functional conservation of funds        assert sum(self.accounts.values()) == initial_total        return Trueledger = FinancialLedger()ledger.deposit("acc1", 500)ledger.deposit("acc2", 200)tx_key = str(uuid.uuid4())assert ledger.transfer(tx_key, "acc1", "acc2", 150) is Trueassert ledger.transfer(tx_key, "acc1", "acc2", 150) is Trueassert ledger.accounts == {"acc1": 350, "acc2": 350}

Key takeaways

  • Properties define conditions that must hold true before, during, and after state changes.
  • Idempotency tokens allow functional operations to be retried safely across networks.
  • Runtime assertions convert formal requirements directly into executable guardrails.

Complexity

  • Time: O(1) amortized for individual validations and lookups; O(K) where K is the number of distinct items or rules processed
  • Space: O(N + M) where N is the number of tracked entities and M is the history of unique transaction identifiers

Evaluating preconditions and transitions takes constant time per entity using hash table lookups. Space scales linearly with the number of unique records and deduplication identifiers preserved to guarantee correctness.

Common mistakes

  • Conflating functional requirements (what the system does) with non-functional requirements (how performant or scalable it is).
  • Applying state mutations before checking all preconditions, leading to inconsistent partial writes upon failure.
  • Omitting the rejection path for negative values or unhandled boundary conditions in business logic.
  • Failing to make write operations idempotent, causing duplicate side effects during automatic retries.

Practice problems

  1. Rate-limited action approval (easy). Hint: Track request timestamps and assert that the current request does not exceed a maximum count within a sliding duration window.
  2. Auction bidding state machine (medium). Hint: Enforce that a new bid must be higher than the current highest bid and that bids are rejected once the auction status moves to closed.
  3. Two-phase distributed transaction coordinator (hard). Hint: Simulate participants voting to prepare, followed by an atomic global commit only if every single participant responds affirmatively.

Summary

Functional requirements define the exact operational capabilities, rules, and state modifications a software system must execute. Implementing them systematically requires parsing specifications into verifiable preconditions, encoding transitions using robust state patterns, and defending system invariants with idempotency and property checks.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!