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

Module-Level Design

Dependency direction, public API and internal implementation

10 min readStage 2 · Frameworks & design8 interview questions
Chapter
Chapter 1 — Design at Multiple Scales
Prerequisites
Topics 1.1–1.2; Volume VI Topics 6.2–6.3
You will be able to
Define modules around business capabilities, design small stable public APIs, hide internal implementation using Java visibility, Spring Modulith and JPMS, keep dependencies acyclic and pointing towards stability, and verify module boundaries automatically
Covers
Dependency direction; Public API; Internal implementation
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Designing Modules Step by Step
  5. 4A. Deep Dive — Named Interfaces, Module Tests and JPMS
  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

A module is a group of classes with a single purpose, a public API through which others use it, and an internal implementation others cannot touch. Module-level design decides module boundaries, what each module exposes, and which modules may depend on which.

A module: public API, hidden implementation
Figure 1 — A module: public API, hidden implementation
ConcernModule-level question
BoundaryWhich capability or concept does this module own?
Public APIWhat is the smallest set of types others need?
Internal implementationWhat can change freely without affecting others?
Dependency directionWhich modules may it use, and which may use it?
Table 1 — Module design concerns

2Why It Exists

As codebases grow beyond what one person can hold in their head, they need units larger than classes but smaller than deployable services. Without explicit modules, any class can use any other; dependencies tangle, cycles form and the codebase becomes a "big ball of mud". Modules — packages with enforced visibility, Maven modules, JPMS modules or Spring Modulith modules — give structure, allow teams to own areas, and are the natural first step before (or instead of) microservices.

3Core Concepts

3.1 Dependency direction

Dependency direction between modules
Figure 2 — Dependency direction between modules

Module dependencies should form a directed acyclic graph (DAG) pointing from volatile (channels, UI, integrations) towards stable (domain core, shared kernel).

RuleRationale
Acyclic Dependencies PrincipleCycles merge modules into one unit of change and release
Stable Dependencies PrincipleDepend on modules more stable than yourself
Stable Abstractions PrincipleStable modules should be abstract (APIs, interfaces, events)
Feature modules don't depend on each other's internalsOnly on published APIs or events
Shared kernel stays tinyEverything depends on it; it must rarely change
Table 2 — Dependency direction rules

When two feature modules need each other, invert one direction (interface owned by the using module) or communicate via events:

JAVA
// orders publishes; billing listens —
// billing depends on orders' event type, not vice versa
package com.shop.orders;                       // module: orders
public record OrderCompleted(OrderId orderId, CustomerId customer, Money total) {}
 
package com.shop.billing;                      // module: billing
@Component
class CreateInvoiceOnOrderCompleted {
    private final Invoices invoices;
    CreateInvoiceOnOrderCompleted(Invoices invoices) { this.invoices = invoices; }
 
    @ApplicationModuleListener  // Spring Modulith: async, transactional event listener
    void on(OrderCompleted event) {
        invoices.createFor(event.orderId(), event.customer(), event.total());
    }
}

3.2 Public API

Public API vs internal implementation
Figure 3 — Public API vs internal implementation

The public API is the module's contract. Design it deliberately:

API design ruleExample
Expose use-case operations, not entitiesOrderService.place(PlaceOrder) returning OrderId
Exchange records/value objects, not JPA entitiesOrderView(id, status, total)
Publish domain events for factsOrderCompleted, OrderCancelled
Keep it smallA few services + DTOs + events
Document and version itJavadoc; deprecation before removal
Test it as a contractModule tests via API only (@ApplicationModuleTest)
Table 3 — Public API design
JAVA
package com.shop.orders;  // API package = module root (Spring Modulith)
 
public interface Orders {                                  // public API
    OrderId place(PlaceOrder command);
    Optional<OrderView> find(OrderId id);
    void cancel(OrderId id, CancellationReason reason);
}
 
public record PlaceOrder(CustomerId customer, List<LineRequest> lines) {}
public record OrderView(OrderId id, OrderStatus status, Money total, Instant placedAt) {}

3.3 Internal implementation

Everything not in the API is internal: entities, repositories, mappers, helpers, adapters. Internals can be refactored, replaced or deleted without notice.

JAVA
package com.shop.orders.internal;  // internal package (hidden by Modulith)
 
@Service
class OrderManagement implements Orders {  // package-private implementation class
    private final OrderRepository repository;
    private final ApplicationEventPublisher events;
    …
}
 
@Entity
class OrderEntity { … }                                   // never leaves the module
 
interface OrderRepository extends JpaRepository<OrderEntity, UUID> {}
Ways to define modules in Java
Figure 4 — Ways to define modules in Java
Hiding mechanismStrengthNotes
Package-private classesCompile-time within one packageBest with few, flat packages per module
Spring Modulith internal packagesVerified by ApplicationModules.verify()Sub-packages are internal unless exposed as named interfaces
Maven/Gradle modulesCompile-time (classpath)Separate artifacts; API module + impl module
JPMS exportsCompile + runtime (strong encapsulation)Non-exported packages inaccessible, even via reflection unless opened
Table 4 — Hiding internals

4How It Works Internally — Designing Modules Step by Step

1. Identify capabilities (ordering, billing, catalogue, shipping) — use domain language and change history, not technical layers.

2. Assign data ownership — each table/entity belongs to one module.

3. Draft APIs — use cases, views and events other modules need.

4. Decide dependency direction — draw the DAG; break needed cycles with events or inversion.

5. Hide internals — package-private, Modulith internal packages or JPMS.

6. Verify automatically — ApplicationModules.verify(), ArchUnit, module-level tests.

7. Document — generated diagrams (Modulith Documenter), ADRs for boundary decisions.

JAVA
class ModularityTests {
    ApplicationModules modules = ApplicationModules.of(ShopApplication.class);
 
    @Test
    // cycles, internal access
    void verifiesModularStructure() {
        modules.verify();
    }
 
    @Test
    // C4-style diagrams
    void writeDocumentation() {
        new Documenter(modules).writeDocumentation();
    }
}

4ADeep Dive — Named Interfaces, Module Tests and JPMS

Spring Modulith named interfaces let a module expose selected sub-packages:

JAVA
@org.springframework.modulith.NamedInterface("spi")
package com.shop.payments.spi;  // other modules may use this sub-package
 
@ApplicationModule(allowedDependencies = { "orders", "payments::spi" })
package com.shop.billing;  // billing may use orders' API and payments' SPI only

Module integration tests bootstrap only one module (and optionally its dependencies), proving the API works in isolation:

JAVA
@ApplicationModuleTest                            // starts only the orders module
class OrdersModuleTests {
    @Autowired Orders orders;
 
    @Test
    void placingAnOrderPublishesEvent(Scenario scenario) {
        scenario.stimulate(() -> orders.place(samplePlaceOrder()))
                .andWaitForEventOfType(OrderPlaced.class)
                .toArriveAndVerify(e ->
                        assertThat(e.total()).isEqualTo(Money.inr("1200.00")));
    }
}

JPMS provides the strongest encapsulation — useful for libraries and platforms:

JAVA
module com.shop.orders {
    requires com.shop.shared;
    requires spring.context;
    exports com.shop.orders;                      // API only
    // reflection for frameworks
    opens com.shop.orders.internal to spring.core, org.hibernate.orm.core;
}
MechanismUse when
Spring ModulithSpring Boot modular monoliths — best balance of enforcement and convenience
Maven/Gradle modulesSeparately versioned or reused libraries; enforced compile boundaries
JPMSLibraries/platforms needing strong encapsulation; less common in Spring apps due to reflection needs
Table 5 — Choosing a module mechanism

5APIs / Features / Syntax

FeaturePurpose
@ApplicationModule(allowedDependencies = …)Declare allowed module dependencies
@NamedInterfaceExpose selected sub-packages
ApplicationModules.verify()Detect cycles and illegal access
@ApplicationModuleListenerTransactional, asynchronous event listener between modules
Event publication registryReliable delivery of module events (outbox-like)
@ApplicationModuleTest, ScenarioModule-scoped integration tests
module-info.java (exports, opens, requires)JPMS encapsulation
Table 6 — Module APIs in Java/Spring

6Practical Examples

6.1 Package-by-layer to package-by-module

controller, service, repository, dto packages were reorganised into orders, billing, catalog, customers modules; each module's internals moved into internal sub-packages. Modulith verification then revealed 14 illegal accesses to fix.

6.2 Shrinking an API

The customers module exposed its JPA entity to 6 modules. Replacing it with CustomerView and CustomerDirectory.find(id) let the team change the entity freely (splitting addresses into their own table) without touching other modules.

6.3 Worked example — modularising a Spring Boot monolith

StepActionResult
1Identify capabilities with domain experts and git change coupling6 modules: catalog, orders, payments, billing, shipping, customers
2Move classes into module root packages (IDE Move Class)Compiles; behaviour unchanged
3Run ApplicationModules.verify()37 violations, 2 cycles
4Break cycle orders ⇄ billing with OrderCompleted eventCycle removed
5Introduce API types (OrderView, CustomerView); move entities to internal packagesViolations → 9
6Fix remaining violations (payments SPI as named interface)0 violations; verification in CI
7Generate module diagrams for documentationLiving architecture docs
Table 7 — Modularisation steps
MetricBeforeAfter
Package cycles2 large cycles0
Classes visible across modules~420~60 (APIs, events)
Change locality (commits touching one module)48%79%
Table 8 — Outcome

6.4 Worked example — designing an API for the payments module

Candidate API elementDecisionReason
PaymentEntityInternalPersistence detail
Payments.authorise(PaymentRequest) → PaymentResult (sealed)PublicUse case other modules need
Payments.refund(PaymentId, Money)PublicUse case
PaymentCaptured, PaymentFailed eventsPublicFacts others react to
RazorpayClientInternal (adapter)Vendor detail
PaymentProvider SPINamed interface spiOther modules may contribute providers
Table 9 — API design decisions

6.5 Worked example — enforcing direction with ArchUnit when not using Modulith

JAVA
@ArchTest
static final ArchRule ordersInternalsStayInternal =
    noClasses().that().resideOutsideOfPackage("com.shop.orders..")
               .should().dependOnClassesThat()
               .resideInAPackage("com.shop.orders.internal..");
// one such rule per module (or generated in a loop over module names)
 
@ArchTest
static final ArchRule noCycles =
    slices().matching("com.shop.(*)..").should().beFreeOfCycles();

Teams without Modulith combine a cycle rule with per-module rules that forbid access to ..internal.. packages from outside the module, achieving a similar effect.

7Common Problems & Mistakes

  • Layer packages mistaken for modules — every feature touches every package.
  • Exposing entities through module APIs.
  • Cycles "just this once" — they spread.
  • A giant common module everyone depends on.
  • Modules without enforcement — boundaries erode within months.
  • Too many tiny modules — coordination overhead without benefit.

8Performance & Production Considerations

AspectNote
Monolith runtimeModules are in-process — no network cost, shared transactions possible
Events between modulesAsync listeners decouple latency; publication registry ensures delivery
Build timesMaven/Gradle modules allow incremental and parallel builds
StartupModule tests start only needed beans — faster CI
Extraction laterClean modules become services with minimal rework
Table 10 — Operational view

Treat module boundaries as a runtime concern as well as a structural one. Events delivered by @ApplicationModuleListener run asynchronously after the publishing transaction commits, so consumers see eventual consistency. The Spring Modulith event publication registry persists each publication, so incomplete ones can be resubmitted after a crash or a listener failure; purge completed entries on a schedule so the table does not grow without bound. Instrument modules individually: Spring Modulith's observability support creates spans for calls between modules, and Micrometer tags on module APIs show which capability drives latency or errors. Keep every table strictly owned by one module, because cross-module joins and shared transactions are what later block service extraction. Splitting Maven or Gradle modules also enables parallel, cached builds that keep CI fast.

9Architecture & Design Considerations

  • Design modules around capabilities and data ownership, validated by change coupling.
  • Keep APIs small and abstract; keep internals truly hidden.
  • Enforce acyclic, stability-directed dependencies automatically.
  • Prefer a modular monolith first; extract services only where independent deployment or scaling pays (Chapter 8).

10Interview Questions & Answers

Q1L1 · BasicConcept

What is a module?

A module is a group of classes with a single purpose that exposes a small public API and hides its internal implementation, so other code can use it without knowing or depending on how it works. In Java it can be a package with package-private internals, a Spring Modulith application module, a Maven or Gradle module, or a JPMS module. Following Parnas, a good module hides a design decision likely to change, such as how orders are stored or how payments are routed to a provider. Modules sit between classes and deployable services: they give teams ownership and structure within one codebase, and are a natural step before, or instead of, microservices.

Q2L1 · BasicConcept

Why should module dependencies be acyclic?

Because a cycle merges the modules involved into one unit of change. If orders depends on billing and billing depends on orders, you cannot understand, test, build, release or extract either one alone; a change in one can ripple back through the other, and the boundary exists only on paper. Acyclic dependencies form a directed graph, so modules can be built and tested bottom-up, and stable modules at the bottom can change rarely while volatile modules at the top change often. Cycles also spread, because once two modules are entangled, adding more cross-calls feels free. Spring Modulith's verify() and ArchUnit's beFreeOfCycles() enforce this automatically.

Q3L2 · IntermediateDesign

What belongs in a module's public API?

The smallest set of types other modules need to use its capability. That usually means a use-case interface such as Orders with place, find and cancel, command and view records such as PlaceOrder and OrderView, identifier value objects, and domain events such as OrderCompleted for facts others react to. It should not include JPA entities, repositories, mappers, adapters or framework types, because exposing them lets other modules depend on internals and freezes them. Every API element is a commitment, so it should be documented, tested as a contract through module tests, and evolved by deprecation before removal. Keeping it small is what lets internals change freely, such as splitting a table.

Q4L2 · IntermediateTrade-off

How can you hide internals in Java?

Java offers four mechanisms of increasing strength. Package-private classes are hidden at compile time, but only within one package, so they suit modules with few, flat packages. Spring Modulith treats sub-packages of a module as internal and checks access with ApplicationModules.verify() in a test, exposing selected sub-packages as named interfaces; it is the most convenient choice for Spring Boot modular monoliths. Separate Maven or Gradle modules enforce boundaries through the build classpath, often as API and implementation artifacts. JPMS exports give strong encapsulation at compile and run time, even against reflection unless packages are opened, which suits libraries but is awkward for reflection-heavy Spring and Hibernate applications.

Q5L3 · Senior EngineerScenario

How do you remove a dependency cycle between two modules?

There are two standard moves. First, invert one dependency: the module that uses something defines the interface it needs, and the other module implements it, so the compile-time arrow now points the other way. Second, decouple with events: instead of orders calling billing and billing calling orders, orders publishes OrderCompleted and billing listens, for example with Spring Modulith's @ApplicationModuleListener, so billing depends on orders' event type but orders knows nothing about billing. A third option, when the two modules are always changed together, is to accept that they are one capability and merge them. After breaking the cycle, add a verification test so it cannot return.

Q6L3 · Senior EngineerInternals

What does Spring Modulith verify?

ApplicationModules.of(ShopApplication.class) builds a model of the modules, treating each direct sub-package of the main application package as a module, and analyses the bytecode with ArchUnit. verify() fails when there are cycles between modules, when one module references types in another module's internal sub-packages instead of its API package or an exposed named interface, and when a module depends on modules outside the allowedDependencies declared in @ApplicationModule. Run as a normal unit test, it puts module boundaries into CI. The same model drives @ApplicationModuleTest, which bootstraps only one module and its dependencies, and the Documenter, which generates C4 and PlantUML module diagrams from the actual code structure.

Q7L4 · Technical ArchitectDesign

How do you choose module boundaries?

I draw boundaries around business capabilities and data ownership, not technical layers. Working with domain experts, I identify capabilities such as catalogue, ordering, payments, billing and shipping, and assign each table or entity to exactly one module. Then I validate the candidates with evidence: Git change coupling should show that most commits touch a single module, and dependencies should form an acyclic graph pointing from volatile to stable modules. Team structure matters too, since a module ideally has one owning team. Boundaries that require constant cross-module calls or shared transactions are probably wrong. Finally I enforce them with Spring Modulith or ArchUnit and revisit them as the domain evolves.

Q8L5 · Solution ArchitectTrade-off

Why start with a modular monolith?

Because it delivers most of the benefits attributed to microservices, such as clear ownership, enforced boundaries and independent evolution of modules, without the costs of distribution: network latency, partial failures, distributed transactions, eventual consistency, many pipelines and far more operational surface. Calls are in process, refactoring across modules is still a single IDE operation, and boundaries are cheap to correct while the team is still learning the domain. If the modules are clean, with small APIs, owned data and event-based collaboration, extracting one into a service later is largely mechanical. Extract only where independent deployment, scaling, technology choice or fault isolation clearly pays for the added complexity.

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.