DEV Community

Saurav Pandey
Saurav Pandey

Posted on

Stop Coupling Your Business Logic: Mastering Hexagonal Architecture

What is Hexagonal Architecture?

Hexagonal Architecture, often called the "Ports and Adapters" pattern, is a design philosophy where your core business logic is kept isolated from external dependencies like databases, APIs, or user interfaces. Instead of your code being tightly coupled to a specific technology, the application communicates with the outside world through defined interfaces (ports) and implementations (adapters).

The Electrical Outlet Analogy

Think of a wall outlet in your home. The "business logic" is the appliance you are using—a toaster, a laptop, or a blender. The "port" is the socket itself, a standard interface that expects a certain voltage and frequency. The "adapter" is the plug attached to your device.

Because the socket follows a strict standard, you can swap your toaster for a laptop, or move from one house to another, without rewiring your entire electrical system. In your software, you want your application code to be the appliance, and your database or web server to be the interchangeable devices that just happen to fit into the ports you’ve built.

Why Does This Matter?

Developers use this to prevent "Big Ball of Mud" architectures, where changing a database schema forces you to rewrite your entire application logic. It allows for easier testing: you can swap a real MySQL database for an in-memory mock during development, or change your Express.js API framework without touching your core domain models. It is the ultimate insurance policy against the shifting landscape of external tools.

A Practical Example in Node.js

Instead of letting the database drive your business logic, you define an interface (a Port) that your service layer uses.

// The Port (Interface definition)
// In Node.js, we enforce this with a class or object structure
class UserRepositoryPort {
  async save(user) { throw new Error('Not implemented'); }
}

// The Domain Logic (The "Hexagon")
class UserService {
  constructor(userRepository) {
    this.userRepository = userRepository;
  }

  async registerUser(userData) {
    return await this.userRepository.save(userData);
  }
}

// The Adapter (MySQL Implementation)
class MySQLUserAdapter extends UserRepositoryPort {
  async save(user) {
    return db.execute('INSERT INTO users...', [user.name]);
  }
}
Enter fullscreen mode Exit fullscreen mode

Takeaway

Hexagonal architecture shifts the focus from "how we store data" to "what the system actually does." By forcing a separation between your business rules and your infrastructure, you regain control over your codebase, making it resilient, testable, and genuinely portable across different technology stacks.


Buy Me A Coffee

Enjoyed this breakdown? Support my open-source work on Buy Me a Coffee or explore react-hook-lab!

Originally published on my blog. You can read the alternative breakdown here.

Top comments (0)