- Chapter
- Chapter 1 — Design at Multiple Scales
- Prerequisites
- Volume VI Chapter 5 (clean functions)
- You will be able to
- Treat the method as the smallest unit of design, assign it one responsibility, distinguish orchestration from computation, shape control flow for readability and correctness, choose between exceptions, results and polymorphism for branching, and relate method-level decisions to class, module and system design
- Covers
- Responsibilities; Control flow
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Designing a Method Step by Step
- 4A. Deep Dive — Pure Core, Imperative Shell at Method Scale
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
Method-level design is the set of decisions about what a single method does (its responsibility) and how it does it (its control flow): inputs, outputs, branching, looping, error paths and side effects.

| Design scale | Primary question | Main tools |
|---|---|---|
| Method | What single task, with what flow? | Naming, decomposition, guard clauses, pattern matching |
| Class | What state and behaviour belong together? | Cohesion, encapsulation |
| Module | What is public, what is hidden, what may it depend on? | APIs, dependency rules |
| Service | What capability, data and team? | API boundaries, ownership |
| System | How do parts interact and where are the boundaries? | Interaction styles, architectural boundaries |
2Why It Exists
Every architectural intention is ultimately implemented in methods. Poorly shaped methods hide rules, duplicate logic, make testing expensive and produce defects in edge cases. Structured programming (Dijkstra, 1968) established that control flow should be understandable from the text; later work on composed methods (Beck), command–query separation (Meyer) and cognitive complexity (SonarSource) refined what "understandable" means. At method scale, design choices are cheap to make and cheap to change — so it is where good habits pay off first.
3Core Concepts
3.1 Responsibilities

A method's responsibility is one task at one level of abstraction. Two kinds of methods are worth distinguishing:
| Kind | Role | Characteristics | Example |
|---|---|---|---|
| Orchestrating (coordinator) | Sequences steps, delegates work | Few branches, calls to named collaborators | placeOrder(cmd) |
| Computing (worker) | Performs a calculation or decision | Pure where possible, no I/O | Money shippingFor(Order) |
| Query | Returns information, no state change | Idempotent, safe to call | boolean isOverdue(LocalDate) |
| Command | Changes state, returns nothing or an id | Named after the effect | void cancel(Reason) |
// Orchestrating method: reads as a use-case script, delegates all work
@Transactional
public OrderId placeOrder(PlaceOrder cmd) {
Customer customer = customers.require(cmd.customerId());
Cart cart = carts.require(cmd.cartId());
PricedCart priced = pricing.price(cart, customer); // computing collaborator
// domain enforces invariants
Order order = Order.place(customer.id(), priced, clock);
orders.save(order);
events.publish(new OrderPlaced(order.id(), order.total()));
return order.id();
}
// Computing method: pure, deterministic, trivial to test
static Money shippingFor(Weight weight, Zone zone, boolean express) {
Money base = zone.ratePerKg().times(weight.kilograms());
return express ? base.times(EXPRESS_FACTOR) : base;
}Signals of too many responsibilities:
| Signal | Example |
|---|---|
| Name contains "and" or is vague | validateAndSave, process, handle |
| Blank lines or comments separating phases | // validate … // calculate … // persist |
| Mixed abstraction levels | Business steps next to string formatting or SQL |
| Many parameters | Inputs for several tasks |
| Hard to name the test | "it works" instead of a specific behaviour |
3.2 Control flow

Control flow design is about making the happy path obvious and every alternative path explicit.
| Technique | Effect | Java form |
|---|---|---|
| Guard clauses / early return | Flat structure; preconditions first | if (x == null) return …; |
| Switch expressions | Exhaustive, value-producing branching | return switch (s) { case … -> … }; |
| Pattern matching over sealed types | Compiler-checked type branching | case Card c -> … |
| Polymorphism | Branching moved into types | shape.area() |
| Streams | Iteration without index bookkeeping | filter/map/reduce |
Optional chains | Absence handled without null ladders | find(id).map(…).orElseThrow() |
| Exceptions | Exceptional paths out of the main flow | throw new InsufficientStock(…) |
// Branching over a closed set of outcomes: exhaustive and flat
public Receipt settle(PaymentResult result, Order order) {
return switch (result) {
case Approved a -> order.markPaid(a.authCode());
case Declined d -> order.markRejected(d.reason());
case PendingReview p -> order.holdUntil(p.deadline());
}; // new result type → compile error here
}| Flow smell | Better flow |
|---|---|
Flag variables controlling loops (boolean found = false) | stream().anyMatch(…), early return |
break/continue with labels | Extract method, return |
| Exceptions used for normal branching | Optional, result types |
Nested try/catch in business logic | Translate exceptions at boundaries (Volume VI, 5.4) |
| Same condition checked in many places | Encapsulate in a predicate method or type |
4How It Works Internally — Designing a Method Step by Step
1. Name the intent before writing code — if you can't, the responsibility is unclear.
2. Define inputs and outputs as types (value objects, records, sealed results) rather than primitives and nulls.
3. List preconditions → guard clauses or validation in value objects.
4. Write the happy path as a short sequence of calls at one level of abstraction.
5. Make alternatives explicit — sealed results, exceptions for violations, Optional for absence.
6. Extract any step whose body is lower-level than its neighbours.
7. Check side effects — are they visible in the name (CQS)?

4ADeep Dive — Pure Core, Imperative Shell at Method Scale
A powerful method-level pattern (Gary Bernhardt's "functional core, imperative shell") splits each use case into:
| Part | Content | Testing |
|---|---|---|
| Pure core methods | Decisions and calculations from inputs to outputs; no I/O, no clock, no randomness | Fast unit tests, property-based tests |
| Imperative shell method | Loads data, calls the core, persists results, sends messages | Few integration tests |
// Imperative shell (orchestrates I/O)
@Transactional
public void applyLateFees(LocalDate today) {
List<Loan> overdue = loans.overdueOn(today);
List<Fee> fees = LateFeePolicy.feesFor(overdue, today); // pure core
fees.forEach(feeRepository::save);
notifier.notifyFees(fees);
}
// Pure core (all decisions)
public final class LateFeePolicy {
static List<Fee> feesFor(List<Loan> loans, LocalDate today) {
return loans.stream()
.filter(l -> l.dueDate().isBefore(today))
.map(l -> new Fee(l.id(), feeFor(l, daysBetween(l.dueDate(), today))))
.toList();
}
static Money feeFor(Loan loan, long daysLate) {
Money raw = loan.dailyFee().times(daysLate);
return raw.min(loan.feeCap());
}
}This shape scales upward: the same separation reappears at class level (domain objects vs services), module level (domain vs adapters) and system level (core services vs integration edges) — a first example of self-similar design.
5APIs / Features / Syntax
| Java 25 feature | Method design benefit |
|---|---|
| Records | Typed inputs/outputs; multiple return values |
Sealed interfaces + pattern matching switch | Exhaustive branching without default |
Record patterns (case Point(var x, var y)) | Deconstruct inputs directly in branches |
Optional | Explicit absence in return types |
Streams, Collectors.teeing, Gatherers (Java 24+) | Declarative collection processing |
var | Less noise in locals |
Unnamed variables _ (Java 22+) | Ignore unused pattern components clearly |
// Record patterns + unnamed variables keep branches compact
static String describe(Shape s) {
return switch (s) {
case Circle(var r) -> "circle r=" + r;
case Rectangle(var w, var h) when w == h -> "square " + w;
case Rectangle(var w, var h) -> "rectangle " + w + "x" + h;
case Triangle(_, _, _) -> "triangle";
};
}6Practical Examples
6.1 From a 90-line handler to a composed method
A Kafka listener that parsed, validated, enriched, persisted and acknowledged messages in one method was split into parse, validate, enrich (pure), store and acknowledge; the listener method became six lines and each step got focused tests.
6.2 Replacing boolean flags with explicit methods
export(report, true, false) became exportAsPdf(report) and exportAsCsv(report); the flag combinations that were never valid disappeared.
6.3 Worked example — redesigning an eligibility method
// Before: mixed responsibilities, nested flow, null returns
public String checkLoan(Applicant a) {
String result = null;
if (a != null) {
if (a.getAge() >= 21) {
if (creditBureau.score(a.getPan()) > 700) {
if (a.getIncome() * 0.4 > requestedEmi(a)) result = "APPROVED";
else result = "REJECTED_AFFORDABILITY";
} else result = "REJECTED_SCORE";
} else result = "REJECTED_AGE";
}
log.info("decision {}", result);
return result;
}// After: typed outcome, pure decision, I/O at the edge
public sealed interface LoanDecision permits Approved, Rejected {}
public record Approved() implements LoanDecision {}
public record Rejected(RejectionReason reason) implements LoanDecision {}
public LoanDecision decide(Applicant applicant) { // shell
CreditScore score = creditBureau.scoreFor(applicant.pan());
LoanDecision decision = LoanRules.decide(applicant, score, requestedEmi(applicant));
audit.record(applicant.id(), decision);
return decision;
}
final class LoanRules { // pure core
static LoanDecision decide(Applicant a, CreditScore s, Money emi) {
if (a.age() < MIN_AGE) return new Rejected(RejectionReason.AGE);
if (s.value() <= MIN_SCORE) return new Rejected(RejectionReason.SCORE);
if (!a.canAfford(emi)) return new Rejected(RejectionReason.AFFORDABILITY);
return new Approved();
}
}| Aspect | Before | After |
|---|---|---|
| Responsibilities per method | 4 (lookup, decide, log, format) | 1 each |
| Cognitive complexity | 12 | 4 (rules), 0 (shell) |
| Outcome type | String with magic values / null | Sealed LoanDecision |
| Test setup for rules | Mock credit bureau and logger | None — plain values |
6.4 Worked example — control flow for batch processing with partial failures
public ImportReport importAll(List<Row> rows) {
List<ImportError> errors = new ArrayList<>();
int imported = 0;
for (Row row : rows) {
switch (RowParser.parse(row)) { // sealed ParseResult
case Parsed(var product) -> { catalog.upsert(product); imported++; }
case Invalid(var line, var problems) ->
errors.add(new ImportError(line, problems));
}
}
return new ImportReport(imported, errors);
}| Design choice | Reason |
|---|---|
| Parse returns a sealed result, not an exception | Invalid rows are expected, not exceptional |
| Errors collected, not thrown | One bad row must not abort the batch |
| Report returned as a record | Caller decides what to do (log, email, fail) |
6.5 Worked example — method-level review checklist
| Question | Good answer |
|---|---|
| Can its responsibility be stated in one short sentence? | "Calculates the late fee for one loan" |
| Is it orchestration or computation — not both? | Orchestration delegates; computation is pure |
| Is the happy path readable top-down without nesting > 2? | Yes, guard clauses first |
| Are alternatives explicit in types? | Sealed result / Optional / domain exception |
| Are side effects visible in the name? | save…, send…, mark… |
| Could it be tested without Spring or mocks? | Yes for computing methods |
7Common Problems & Mistakes
- Mixing orchestration and computation — untestable business rules inside I/O code.
- Nested conditionals where guard clauses or polymorphism would flatten flow.
- Strings, ints and nulls as outcomes instead of types.
- Exceptions for expected outcomes (invalid rows, declined payments).
- Hidden side effects in query-named methods.
- Over-fragmentation into many trivial methods that obscure flow.
8Performance & Production Considerations
| Aspect | Note |
|---|---|
| Small methods | Inlined by the JIT; no measurable cost |
| Pure cores | Easy to cache, parallelise and reason about under concurrency |
| Exceptions on hot paths | Expensive stack traces — use result types for expected failures |
| Streams vs loops | Negligible difference in most code; measure hot loops with JMH |
| Diagnostics | Named steps produce readable stack traces and logs |
9Architecture & Design Considerations
- Keep decisions in pure methods and I/O in thin orchestrators — the seed of hexagonal architecture.
- Use types for outcomes so that method contracts become explicit API contracts at higher scales.
- Enforce complexity limits for new methods through quality gates.
- Review method design in the context of the class and module it belongs to.
10Interview Questions & Answers
What makes a method well designed?
A well-designed method does one thing at one level of abstraction, so it reads like a short description of a step. Its name says what it does, such as calculateShippingCost, not how. Its control flow is simple, with guard clauses for preconditions rather than deep nesting. Its inputs and outputs are explicit: it takes what it needs as parameters and returns a result, rather than reading and writing hidden state. Any side effects, such as saving data or sending messages, are visible from its name or its place in the design. Such methods are easy to read, test and reuse.
What is a guard clause?
A guard clause is a check at the start of a method that handles a special case or invalid precondition immediately, by returning early or throwing an exception. For example, if (order.isEmpty()) return Money.ZERO; or Objects.requireNonNull(customer). After the guards, the rest of the method can focus on the normal case without wrapping it in nested if statements. This keeps the main path at the left margin and easy to read, and makes the preconditions explicit and visible at a glance. Long chains of nested conditions are a common sign that guard clauses would help.
What is the difference between orchestrating and computing methods?
An orchestrating method coordinates a process: it calls other methods in sequence, loads data, invokes calculations and saves results, but contains little logic itself. An application service method such as placeOrder is typical. A computing method performs a calculation or decision, such as working out a discount or checking eligibility, and ideally has no side effects, so its result depends only on its inputs. Separating the two keeps orchestrating methods short and readable, and makes computing methods easy to unit-test exhaustively without mocks. Mixing them produces long methods where business rules are buried among I/O calls.
How do sealed types improve control flow?
A sealed interface lists exactly which types may implement it, such as Approved, Rejected and NeedsReview for an eligibility result. A switch expression that pattern-matches over a sealed type must handle every permitted case, and the compiler checks that it does. So no default branch is needed to catch unexpected cases, and if a new variant is added later, every switch that does not handle it fails to compile. This turns a whole category of runtime bugs into compile errors. Each variant can also carry its own data, such as a rejection reason, which is clearer than flags and nullable fields.
When should a method return a result type instead of throwing?
Use a result type when the alternative outcome is a normal, expected part of the business process rather than an error. A loan application being rejected, a coupon being expired or a row in an import file failing validation are all expected, and callers must handle them. Returning a sealed result, such as Approved or Rejected with a reason, makes every outcome explicit in the method signature and lets the compiler check handling. Exceptions are better for unexpected failures, such as a database being unavailable, broken invariants or programming errors, which callers usually cannot handle locally.
What is "functional core, imperative shell"?
"Functional core, imperative shell" is a way of structuring code so that decisions and side effects are separated. The core consists of pure functions over immutable data: given the current state and an input, they compute a decision or new state, such as which order lines to ship. The shell is a thin layer that performs I/O: it loads data, calls the core and saves results or sends messages. The core can be unit-tested exhaustively without mocks and reused in any context, while the shell is simple enough to cover with a few integration tests. It works well with hexagonal architecture.
How do method-level decisions affect architecture?
Architecture is built from methods, so method-level habits decide whether architectural boundaries can exist. If business rules are embedded inside methods that also call databases and external APIs, the domain cannot be separated from infrastructure, ports and adapters cannot be introduced and modules cannot be tested in isolation. If decisions live in pure methods that take data and return results, the domain naturally becomes independent of technology, and the orchestrating code becomes a thin layer that maps cleanly to application services and adapters. Good method design is therefore a precondition for clean modules, testability and later service extraction.
Why should a solution architect care about method design?
Architecture diagrams describe intent, but the system's real architecture is whatever the code does. If methods mix business rules with I/O, ignore module boundaries or hide side effects, the architecture erodes no matter how good the diagram is, and the system becomes expensive to change. A solution architect does not review every method, but should set and reinforce the practices that keep boundaries intact: clear separation of decisions and side effects, explicit result types, small focused methods and automated architecture tests. Spot-checking method design in key areas during reviews is an effective early warning of structural problems.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.