Sobes.tech
Junior — Middle

Explain the concept of a port in the context of hexagonal architecture and its role in the system.

sobes.tech AI

Answer from AI

In hexagonal architecture (also known as Ports and Adapters), a port is an abstract interface that defines how external components (adapters) interact with the core of the application (domain logic).

Role of a port:

  • Defines contracts for incoming and outgoing interactions.
  • Isolates business logic from implementation details of external systems (databases, UI, APIs, etc.).
  • Allows easy swapping of external components without changing the core application.

For example, if you have a service that needs to save data, a port could be an interface with a method save(data). An external adapter implements this interface, for example, saving data to a database or sending it to a queue.

This ensures system flexibility and testability, as adapters can be replaced without affecting the main logic.

Example of a port in Python:

from abc import ABC, abstractmethod

class UserRepositoryPort(ABC):
    @abstractmethod
    def save_user(self, user):
        pass

# Adapter implementing the port
class UserRepositoryDB(UserRepositoryPort):
    def save_user(self, user):
        # code to save to database
        pass

# In the core of the application, we use the port, independent of implementation
class UserService:
    def __init__(self, user_repo: UserRepositoryPort):
        self.user_repo = user_repo

    def register_user(self, user):
        self.user_repo.save_user(user)
Explain the concept of a port in the context of… - sobes.tech