Product engineering

Separate Business Rules from Transport Code

Give business rules a clear home outside request parsing while preserving authorization, transactions and explicit side-effect boundaries.

A business rule should remain understandable when the same operation is triggered by a web request, a background job or an administrative tool. If the rule exists only inside one HTTP handler, another entry point may accidentally implement a different version. Separating the rule from transport code makes that boundary easier to test and maintain.

Microsoft’s guidance on N-tier architecture discusses separation of responsibilities across application layers. A small product does not need to adopt a large layered architecture to benefit from that distinction. The practical goal is to keep request parsing and response formatting from becoming the only place where the application’s meaning exists.

Identify a rule with a clear domain meaning

Start with a rule the product can describe without naming HTTP, JSON or a database table. For a fictional reservation system, a rule might say that a confirmed reservation cannot exceed the available capacity for its slot. Another might define which transitions are allowed after cancellation.

Separate those rules from interface validation. Checking that a request contains a string is different from deciding whether the requested transition is valid for the reservation’s current state. Both checks matter, but they belong to different levels of meaning.

Avoid extracting every conditional into a new abstraction. Focus on rules that are shared, consequential or difficult to understand inside transport code. A useful boundary should reduce ambiguity, not produce a collection of tiny functions whose names merely restate the syntax.

Describe the operation’s inputs and outcome

Define an application-level input that represents the user’s intention. It should contain validated values and the relevant actor context, without requiring the business operation to understand framework request objects or raw headers.

Return an outcome that describes success or a meaningful failure. The transport layer can then map that result to an HTTP response, a job status or a command-line message. This keeps protocol choices from becoming the business model itself.

For the reservation example, the operation might return confirmed, capacity unavailable or invalid state transition. The HTTP layer decides which documented response represents each outcome. A background worker can use the same result without pretending to be a web server.

Keep parsing at the boundary

The transport layer should decode the request, validate its basic shape and establish the authenticated context through the appropriate mechanism. It then calls the application operation with a clear input model.

Do not pass the entire request object simply because it is convenient. That creates hidden dependencies on cookies, headers or framework state that make the rule difficult to reuse and test. Pass only the values the operation actually needs.

Keep error handling explicit. A malformed request may be rejected before the business operation runs, while a valid request can still fail a domain rule. The caller should receive a coherent response, but the implementation should preserve the distinction for testing and diagnostics.

Enforce authorization at a deliberate point

Authentication identifies the caller; authorization determines whether the caller may perform the operation on the resource. The application boundary needs a reliable policy for this check, especially when several transports can invoke the same behavior.

Do not assume that an HTTP middleware check protects a background or administrative path automatically. Identify which layer enforces resource-level access and ensure all relevant entry points use it. The design should make bypasses visible rather than relying on convention alone.

Pass a bounded actor context instead of a large user object containing unrelated personal data. The operation may need an account identifier and permissions, not a complete profile. This keeps the interface clearer and reduces accidental propagation of sensitive information.

Separate decision logic from external effects

A rule that calculates whether a transition is allowed can often be expressed independently from sending emails or calling a provider. Keeping those responsibilities distinguishable makes tests more focused and failures easier to reason about.

This does not mean every application needs a complex event bus. A straightforward application service can coordinate the steps while keeping the rule’s input and result explicit. Choose the simplest structure that preserves the relevant boundaries.

For the reservation system, determine the allowed transition, apply it through a controlled persistence operation and then handle the required notification through the chosen reliable mechanism. Do not let an email timeout silently redefine whether the reservation itself exists.

Respect transaction and concurrency boundaries

Moving logic into a domain function does not automatically make it correct under concurrency. A capacity check based on stale data can still allow overbooking if the subsequent write is not protected. The business invariant needs enforcement at the appropriate storage boundary.

Design the operation and repository interaction together. Decide what must happen atomically and which failures can leave partial state. A clean class diagram is not evidence that the transaction semantics are safe.

Keep tests at both levels. Pure rule tests can cover allowed and rejected transitions quickly, while persistence-level tests verify the concurrency and atomicity assumptions. Each test layer answers a different question, and neither should pretend to replace the other.

Use interfaces only where they clarify dependencies

An interface can express the operation’s need for storage, time or an external service without binding it to one implementation. It is useful when the boundary supports testing, replacement or independent reasoning about side effects.

Avoid creating an interface for every class by habit. An abstraction with one trivial method and no meaningful boundary can add indirection without improving the design. Evaluate whether the interface makes the business operation easier to understand or merely increases the number of files.

Name interfaces around the capability the application needs. A reservation repository or notification sender can be more useful than a generic database manager with dozens of unrelated methods. A narrow contract also limits what test doubles must simulate.

Make time and nondeterminism explicit

Business rules often depend on the current time, generated identifiers or external state. Reading those values invisibly inside many functions makes tests less predictable. Pass or inject them at a suitable boundary when the rule needs controlled evaluation.

For example, a cancellation deadline should use a documented timezone and time source. A test can then evaluate the instant before, at and after the boundary without waiting for the wall clock. The product’s intended rule remains visible.

Do not overgeneralize this into a framework for every value. Keep the design focused on nondeterminism that affects correctness. A small explicit dependency is often enough to make the rule testable without introducing an elaborate architecture.

Share behavior across transports without sharing assumptions

When adding a background job or administrative command, call the same application operation where the business meaning is the same. Let the new transport handle its own parsing, authentication context and output representation.

Review differences in execution conditions. A job may retry, run later or operate without an interactive user. It may need a service identity and an idempotency strategy. Reusing the rule does not eliminate those transport-specific responsibilities.

If the operation’s meaning differs, do not force reuse merely to avoid duplicated lines. A customer cancellation and an administrative correction may have different authorization, audit and notification requirements. Share the common rule carefully while keeping the distinct use cases explicit.

Test rules with examples that explain the policy

Choose test names and data that express the business condition. A test showing that a canceled reservation cannot be confirmed again without a new operation is easier to understand than one describing an internal helper’s branch number.

Include boundaries and relevant combinations. For capacity, consider zero remaining places and competing updates. For deadlines, test the defined instant and timezone behavior. Use synthetic data that is minimal enough to reveal why the outcome follows.

Do not reproduce the implementation in the assertion. If the test calculates the expected result through the same formula as the code, both can share the same error. Prefer examples derived from the documented rule and independent reasoning.

Refactor incrementally from a real use case

Start with one handler whose business meaning is difficult to see. Write or preserve tests for its observable behavior, extract a coherent operation and keep the transport mapping small. Avoid reorganizing the entire application before proving that the new boundary helps.

Review the resulting call path with another engineer. Can they identify where input is parsed, access is checked, the rule is applied and side effects occur? If the answer requires jumping through many generic layers, simplify the design.

Keep deployment behavior unchanged during a structural refactor unless a behavior change is explicitly part of the task. Mixing a new rule with a large extraction makes failures harder to attribute and review.

Judge the boundary by maintainability

A successful separation makes the policy easier to explain, test and invoke consistently. It does not need to satisfy a particular architectural label. The implementation should fit the product’s size and the team’s ability to operate it.

Revisit the boundary when new transports, rules or persistence needs appear. Some abstractions will grow, while others can remain simple functions. The enduring principle is that the product’s decisions deserve a clear home, independent of the mechanism that happened to deliver the request.

Continue reading

Choose Cache Invalidation Rules for a Read-Heavy Feature

Keep Test Fixtures Small, Clear and Safe