Sobes.tech
Senior

Tell me about clean architecture and onion architecture

sobes.tech AI

Answer from AI

Clean Architecture is an approach to software design that separates the system into layers with clear dependencies directed inward. The main idea is to separate business logic from implementation details (UI, databases, external services).

Main layers:

  • Entities — business rules
  • Use Cases — application business logic
  • Interface Adapters — adapters for UI, databases, external APIs
  • Frameworks & Drivers — external details (UI, DB, web)

Dependencies are directed from outer layers to inner layers, which facilitates testing and maintenance.

Onion Architecture is very similar in concept to Clean Architecture. It also builds layers resembling an onion, where the inner layers are the core business logic, and the outer layers are infrastructure and UI. An important principle is that dependencies are directed inward, and outer layers can depend on inner layers, but not vice versa.

Example in Go:

// Inner layer: business logic
package entity

type User struct {
    ID   int
    Name string
}

// Use case
package usecase

import "yourapp/entity"

type UserRepository interface {
    GetUser(id int) (*entity.User, error)
}

func GetUserName(repo UserRepository, id int) (string, error) {
    user, err := repo.GetUser(id)
    if err != nil {
        return "", err
    }
    return user.Name, nil
}

Here, usecase depends on entity and the repository interface, but not on a specific database implementation.

Thus, both architectures aim to create flexible, easily testable, and maintainable systems through separation of concerns and dependency control.