Video in progress

Strong Middle 🧱 OOP and SOLID

What are a port and an adapter in hexagonal (ports and adapters) architecture? What principle is it based on?

A port is an interface declared by the domain or use-case layer, and an adapter is the implementation that connects it to a technology (HTTP, JPA, Kafka). The basis is Dependency Inversion: dependencies point from the outside in, and the domain knows no framework.

📖 Answer

There are two kinds of ports:

  • Inbound (driving) ports say what the application can do: PlaceOrderUseCase. A REST controller, a CLI or a Kafka consumer calls it.
  • Outbound (driven) ports say what the application needs from the outside: LoadOrderPort, PaymentGateway. A JPA repository or an HTTP client implements it.
adapter.in.web      → OrderController       (calls port.in)
application         → PlaceOrderService      (implements port.in, uses port.out)
application.port.in → PlaceOrderUseCase
application.port.out→ PaymentGateway, OrderStore
domain              → Order, Money, OrderLine (no framework)
adapter.out.jpa     → JpaOrderStore          (implements port.out)
adapter.out.payme   → PaymeGateway

What it gives you:

  • you can unit test the domain and the use cases without the Spring context or a DB;
  • switching the payment provider happens at the level of a single adapter;
  • JPA annotations don't "pollute" the domain model (if you make a separate persistence model).

The cost:

  • for every entity there is a domain model + a JPA model + a mapper, so the amount of code grows;
  • for a simple CRUD service this is overkill and violates KISS.

My practical approach: guard the layer boundaries with an ArchUnit test (the domain package must not depend on org.springframework), and allow using the JPA entity as the domain model if the domain isn't complex. You split them when complexity grows.