Hexagonal architecture (ports and adapters, by Alistair Cockburn) puts the application core at the centre and isolates it from technology details. Structure - Domain and application core: entities, business rules and use cases. Pure Java, with no Spring, JPA or HTTP dependencies. - Ports: interfaces defined by the core. - Inbound (driving) ports describe what the application offers: PlaceOrderUseCase. - Outbound (driven) ports describe what it needs: OrderRepository, PaymentGateway, EventPublisher. - Adapters: implementations at the edges. - Inbound adapters: REST controllers, Kafka listeners, CLI or scheduled jobs calling the inbound ports. - Outbound adapters: JPA repositories, HTTP clients, Kafka producers implementing the outbound ports. Dependencies always point inward: adapters depend on ports, never the reverse. public interface PaymentGateway { PaymentResult charge(Money amount, PaymentMethod method); } // port in the core @Component class RazorpayPaymentAdapter implements PaymentGateway { ... } // adapter in infrastructure Benefits - Business logic is testable without databases or web servers (in-memory adapters in tests). - Technology can change (switch payment provider, database or messaging) with limited impact. - Clear boundaries for large teams; architecture tests (ArchUnit) can enforce dependency rules. When extra ports and adapters add more complexity than value - CRUD-heavy services with little business logic: wrapping Spring Data repositories in hand-written ports and mapping identical objects between JPA entities, domain models and DTOs multiplies code without benefit. - Ports with exactly one implementation that is never swapped and never faked in tests. - Duplicate models in every layer that differ only in name, leading to mapping bugs and slower development. - Small teams or short-lived services where simplicity and delivery speed matter more. - Performance-sensitive reads where projections directly from the database are far simpler than going through domain objects. A pragmatic approach - Apply hexagonal structure where the domain is complex or external integrations are volatile (payments, third-party APIs). - Allow simple modules to use a layered or vertical-slice structure, letting read queries bypass the domain. - Introduce a port when there is a concrete reason: multiple implementations, test isolation of external systems, or a boundary between teams. Good architecture is measured by how easy it is to change the system, not by the number of layers.
Ravindra Wadile · · 0 likes