Browse Java Design Patterns & Enterprise Application Architecture

Iteration and Recursion in Composites

Choose traversal style for Java composites deliberately, balancing recursion, explicit iterators, streams, and failure handling.

Composite almost always leads to traversal design questions.

Recursion Is The Natural Default

For many Java composites, recursion keeps the code closest to the model:

1public Money total() {
2    return children.stream()
3        .map(PriceNode::total)
4        .reduce(Money.zero(), Money::add);
5}

That is often enough when:

  • trees are not extremely deep
  • the operation is simple
  • traversal order is obvious

When Explicit Iteration Helps

Use explicit iteration when you need:

  • stack-safe traversal of very deep structures
  • control over traversal order
  • pause/resume behavior
  • incremental streaming of results

At that point, a dedicated iterator, visitor, or traversal service may be clearer than hiding everything inside one recursive method.

Failure Semantics Matter

Ask what happens when traversal fails on one child:

  • stop immediately
  • collect partial failures
  • continue best-effort
  • return a structured result

Recursive elegance does not remove that design choice.

Review Rule

Keep traversal logic close to the model only while it remains understandable. If traversal rules start carrying policy, filtering, or complex failure handling, pull them into a dedicated collaborator.

Loading quiz…
Revised on Thursday, April 23, 2026