Sobes.tech
Junior — Middle

What are the signs indicating the use of hexagonal architecture in the code?

sobes.tech AI

Answer from AI

Hexagonal architecture (or Ports and Adapters) is characterized by the following features:

  • Clear separation between the core and external interfaces. The application core contains business logic and does not depend on external systems.
  • Use of ports and adapters. Ports are interfaces through which the core interacts with the outside world, and adapters are specific implementations of these interfaces.
  • No direct dependencies of the core on infrastructure. For example, business logic does not depend on databases, UI, or network protocols.
  • Testability. Thanks to the isolation of business logic, it is easy to write unit tests by mocking adapters.

Example in Python:

from abc import ABC, abstractmethod

# Port (interface)
class UserRepository(ABC):
    @abstractmethod
    def get_user(self, user_id: int):
        pass

# Application core
class UserService:
    def __init__(self, user_repo: UserRepository):
        self.user_repo = user_repo

    def get_user_name(self, user_id: int) -> str:
        user = self.user_repo.get_user(user_id)
        return user.name

# Adapter (concrete implementation of the port)
class InMemoryUserRepository(UserRepository):
    def __init__(self):
        self.users = {1: type('User', (), {'name': 'Alice'})()}

    def get_user(self, user_id: int):
        return self.users.get(user_id)

# Usage
repo = InMemoryUserRepository()
service = UserService(repo)
print(service.get_user_name(1))  # Alice

In this example, the business logic (UserService) does not depend on the specific storage implementation (InMemoryUserRepository). This is a characteristic of hexagonal architecture.

What are the signs indicating the use of hexagonal… - sobes.tech