Sobes.tech
Junior — Middle

Can you explain the role of an adapter in hexagonal architecture and how it facilitates interaction between components?

sobes.tech AI

Answer from AI

In hexagonal architecture (also known as Ports and Adapters), adapters serve as a bridge between the application's core and external systems (such as databases, web services, user interfaces).

The role of an adapter is to transform data and calls between the internal domain format and protocol, and the external interfaces. This ensures loose coupling and isolation of business logic from external implementation details.

For example, if you have a service implementing business logic, a database adapter would convert domain objects into database queries and back. Similarly, a web interface adapter would accept HTTP requests, transform them into domain calls, and return responses.

An example in Python (simplified):

class UserService:
    def __init__(self, user_repo):
        self.user_repo = user_repo

    def get_user(self, user_id):
        return self.user_repo.find_by_id(user_id)

# Database adapter
class UserRepositoryAdapter:
    def __init__(self, db_connection):
        self.db = db_connection

    def find_by_id(self, user_id):
        # transforming database query
        result = self.db.query(f"SELECT * FROM users WHERE id = {user_id}")
        # transforming result into a domain object
        return User(result['id'], result['name'])

Thus, adapters facilitate interaction between components, maintaining the purity and independence of business logic.