ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 5 · Software Design & Design Patterns
  4. Volume VII
  5. Method-Level Design
Book 5 · Volume VII — Advanced Design & Architecture-Level Design Decisions · Topic 1.1

Method-Level Design

Responsibilities and control flow

9 min readStage 2 · Frameworks & design8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Designing a Method Step by Step
  5. 4A. Deep Dive — Pure Core, Imperative Shell at Method Scale
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 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 at multiple scales
Figure 1 — Design at multiple scales
Design scalePrimary questionMain tools
MethodWhat single task, with what flow?Naming, decomposition, guard clauses, pattern matching
ClassWhat state and behaviour belong together?Cohesion, encapsulation
ModuleWhat is public, what is hidden, what may it depend on?APIs, dependency rules
ServiceWhat capability, data and team?API boundaries, ownership
SystemHow do parts interact and where are the boundaries?Interaction styles, architectural boundaries
Table 1 — Where method design sits

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

Method responsibility
Figure 2 — Method responsibility

A method's responsibility is one task at one level of abstraction. Two kinds of methods are worth distinguishing:

KindRoleCharacteristicsExample
Orchestrating (coordinator)Sequences steps, delegates workFew branches, calls to named collaboratorsplaceOrder(cmd)
Computing (worker)Performs a calculation or decisionPure where possible, no I/OMoney shippingFor(Order)
QueryReturns information, no state changeIdempotent, safe to callboolean isOverdue(LocalDate)
CommandChanges state, returns nothing or an idNamed after the effectvoid cancel(Reason)
Table 2 — Kinds of methods
JAVA
// 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:

SignalExample
Name contains "and" or is vaguevalidateAndSave, process, handle
Blank lines or comments separating phases// validate … // calculate … // persist
Mixed abstraction levelsBusiness steps next to string formatting or SQL
Many parametersInputs for several tasks
Hard to name the test"it works" instead of a specific behaviour
Table 3 — Responsibility smells

3.2 Control flow

Control flow: arrow code vs guard clauses
Figure 3 — Control flow: arrow code vs guard clauses

Control flow design is about making the happy path obvious and every alternative path explicit.

TechniqueEffectJava form
Guard clauses / early returnFlat structure; preconditions firstif (x == null) return …;
Switch expressionsExhaustive, value-producing branchingreturn switch (s) { case … -> … };
Pattern matching over sealed typesCompiler-checked type branchingcase Card c -> …
PolymorphismBranching moved into typesshape.area()
StreamsIteration without index bookkeepingfilter/map/reduce
Optional chainsAbsence handled without null laddersfind(id).map(…).orElseThrow()
ExceptionsExceptional paths out of the main flowthrow new InsufficientStock(…)
Table 4 — Control-flow tools
JAVA
// 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 smellBetter flow
Flag variables controlling loops (boolean found = false)stream().anyMatch(…), early return
break/continue with labelsExtract method, return
Exceptions used for normal branchingOptional, result types
Nested try/catch in business logicTranslate exceptions at boundaries (Volume VI, 5.4)
Same condition checked in many placesEncapsulate in a predicate method or type
Table 5 — Control-flow smells

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)?

Method-level design decisions
Figure 4 — Method-level design decisions

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:

PartContentTesting
Pure core methodsDecisions and calculations from inputs to outputs; no I/O, no clock, no randomnessFast unit tests, property-based tests
Imperative shell methodLoads data, calls the core, persists results, sends messagesFew integration tests
Table 6 — Functional core, imperative shell
JAVA
// 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 featureMethod design benefit
RecordsTyped inputs/outputs; multiple return values
Sealed interfaces + pattern matching switchExhaustive branching without default
Record patterns (case Point(var x, var y))Deconstruct inputs directly in branches
OptionalExplicit absence in return types
Streams, Collectors.teeing, Gatherers (Java 24+)Declarative collection processing
varLess noise in locals
Unnamed variables _ (Java 22+)Ignore unused pattern components clearly
Table 7 — Language features for method design
JAVA
// 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

JAVA
// 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;
}
JAVA
// 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();
    }
}
AspectBeforeAfter
Responsibilities per method4 (lookup, decide, log, format)1 each
Cognitive complexity124 (rules), 0 (shell)
Outcome typeString with magic values / nullSealed LoanDecision
Test setup for rulesMock credit bureau and loggerNone — plain values
Table 8 — Redesign outcome

6.4 Worked example — control flow for batch processing with partial failures

JAVA
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 choiceReason
Parse returns a sealed result, not an exceptionInvalid rows are expected, not exceptional
Errors collected, not thrownOne bad row must not abort the batch
Report returned as a recordCaller decides what to do (log, email, fail)
Table 9 — Flow decisions for partial failure

6.5 Worked example — method-level review checklist

QuestionGood 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
Table 10 — Method design review

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

AspectNote
Small methodsInlined by the JIT; no measurable cost
Pure coresEasy to cache, parallelise and reason about under concurrency
Exceptions on hot pathsExpensive stack traces — use result types for expected failures
Streams vs loopsNegligible difference in most code; measure hot loops with JMH
DiagnosticsNamed steps produce readable stack traces and logs
Table 11 — Runtime view

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

Q1L1 · BasicConcept

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.

Q2L1 · BasicCode

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.

Q3L2 · IntermediateConcept

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.

Q4L2 · IntermediateCode

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.

Q5L3 · Senior EngineerTrade-off

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.

Q6L3 · Senior EngineerConcept

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.

Q7L4 · Technical ArchitectDesign

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.

Q8L5 · Solution ArchitectConcept

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.