The user wants a plan for a "Dependency Inversion Initiative" to decouple domain logic from frameworks using adapter ports.
This implies implementing the "Ports and Adapters" architecture (also known as Hexagonal Architecture) or a similar pattern (Onion Architecture, Clean Architecture).
Key Concepts:
Domain Logic (Core): The business rules, entities, and use cases. It should know nothing about the outside world (DBs, UIs, Frameworks).
Frameworks: Libraries like Spring Boot, Django, Express, ORMs (Hibernate), etc.
Dependency Inversion Principle (DIP): High-level modules (Domain) should not depend on low-level modules (Infrastructure). Both should depend on abstractions.
Ports: Interfaces defined by the Domain.
Driving/Primary Ports: APIs called by the outside world to do something (Use Cases).
Driven/Secondary Ports: Interfaces the Domain needs to interact with the outside world (Repositories, External Services).
Structure of the Plan:
I need to structure this as a professional initiative or project proposal. It should have phases, specific tasks, code examples (conceptual or pseudo-code), and risk mitigation.
Phase 1: Assessment & Education
Analyze current coupling.
Educate the team (it's a paradigm shift).
Define the scope (Greenfield vs. Brownfield/Refactoring). Assuming Brownfield for a more complex/realistic scenario, but keeping it general enough.
Phase 2: Architecture Design (The "Blueprint")
Define the Core Domain.
Define Ports (Interfaces).
Select the pattern (Hexagonal is the specific one mentioned via "adapter ports").
Phase 3: Implementation Strategy (The "How-To")
Folder structure.
Code separation.
Dependency Injection container usage (crucial for wiring adapters to ports).
Phase 4: The Migration (The "Process")
Extract interface.
Move implementation to infrastructure.
Inject dependency.
Test coverage (unit tests become easier now).
Phase 5: Governance & Maintenance
Linters/ArchUnit (to enforce the boundaries).
Drafting the Content - Specific Details to Include:
Visual aid: Describe the concentric circles or hexagon.
Code: Show a UseCase interface, a Service implementation, a Repository interface, and a JpaRepository adapter.
Tools: Mention ArchUnit (Java), NetArchTest (C#), or similar tools to enforce architecture programmatically.
Refining the Tone:
The tone should be technical, strategic, and actionable. It should appeal to a CTO or Lead Architect.
Step-by-Step Plan Construction:
Title: Strategic Plan for Dependency Inversion via Ports & Adapters.
Objective: Explicitly state the goal (decoupling).
Let's write it out.
This initiative plan outlines the transition from a coupled architecture (where business logic depends on frameworks) to a Hexagonal Architecture (Ports and Adapters).
The goal is to ensure your domain logic knows nothing about databases, web frameworks, or external APIs. It only knows about interfaces (Ports) that you define.
To eliminate technical debt caused by framework lock-in by moving from a Framework-Centric architecture to a Hexagonal (Ports & Adapters) architecture.
Current State: Domain entities extend ORM classes (e.g., ActiveRecord, Doctrine Entity) and business logic resides in Controllers.
Target State: Domain logic is pure (POJOs/POCOs/plain classes). Frameworks are treated as plugins via Adapters.
2. Architecture Blueprint
We will enforce the Dependency Inversion Principle (DIP). High-level modules (Domain) must not depend on low-level modules (Infrastructure). Both must depend on abstractions.
The Hierarchy
Domain (Center): Pure business logic, Entities, Value Objects. Zero dependencies.
Application (Shell): Use Cases (Services) and Port Interfaces (API contracts).
Infrastructure (Outer):Adapters (Implementations) for DBs, Web Frameworks, Message Queues.
3. Phase 1: Foundation & Stabilization (Weeks 1-2)
Goal: Define the boundaries and interface contracts.
1.1 Define "Driving" (Primary) Ports
These are interfaces that define how the outside world talks to your application.
Action: Create UseCase or Service interfaces in the Application layer.
Example:CreateOrderUseCase interface defines a method execute(orderData).
1.2 Define "Driven" (Secondary) Ports
These are interfaces that define how your application talks to the outside world.
Action: Create Repository interfaces and Gateway interfaces in the Domain/Application layer.
Crucial Step: These interfaces must belong to the Domain, not the infrastructure.
Example:OrderRepository interface defines save(order). Note: No SQL or ORM types allowed in the signature.
1.3 The "Pure" Entity Extraction
Action: Identify core entities.
Refactoring: Remove all framework annotations (e.g., @Entity, @Table) and imports from the domain classes. The Domain class should be a standard data structure (e.g., a plain Class with getters/setters and business methods).
4. Phase 2: The Inversion (Weeks 3-6)
Goal: Implement the Adapters and decouple the data flow.
4.1 Implement Infrastructure Adapters
This is where the Dependency Inversion actually happens.
Action: Create concrete classes in the Infrastructure layer that implement the Ports defined in Phase 1.
This class contains the ORM code (e.g., Eloquent, Hibernate, TypeORM).
It handles the mapping: converting the Pure Domain Entity into an ORM Model to save to the DB, and vice versa for retrieval.
4.2 Implement Controller Adapters
Action: Move logic out of framework Controllers.
Refactoring: Framework Controllers become simple dispatchers. They receive an HTTP request, transform JSON/Params into a DTO (Data Transfer Object), and call the Use Case Interface (Port). They should contain no business logic.
4.3 Dependency Injection Wiring
Action: Configure the DI Container (e.g., Spring IoC, .NET ServiceCollection, Awilix).
Rule: The container must inject the Adapter Implementation wherever a Port Interface is requested.
5. Phase 3: Migration Strategy (The "Strangler Fig" Pattern)
Goal: safely transition without a big-bang rewrite.
Approach A: The Anti-Corruption Layer (ACL)
If integrating with a legacy system, build an Adapter that translates the legacy messy data model into your clean Domain Model.
Approach B: Feature Toggle
Write the new Port and Adapter.
Use a feature flag to switch execution between the "Old Direct Framework Code" and the "New Hexagonal Code."
Verify data consistency.
Delete the old code.
6. Code Example: The Mental Shift
Before (Coupled)
The entity depends on the database framework.
// BAD: Domain logic is coupled to the ORM
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
email: string;
// Logic mixed with DB definition
isValidEmail() { return this.email.includes("@"); }
}
After (Decoupled via Ports)
1. The Domain (Pure)
// GOOD: Pure domain logic, no imports
export class User {
constructor(public id: number, public email: string) {}
isValidEmail(): boolean {
return this.email.includes("@");
}
}
2. The Port (Interface)
// Defined by the application, implemented by infrastructure
export interface UserRepository {
save(user: User): Promise<void>;
findById(id: number): Promise<User | null>;
}
3. The Adapter (Infrastructure)
// The Adapter bridges the gap
import { UserRepository } from "../application/ports";
import { UserORM } from "./db/entities"; // Framework specific
import { User } from "../domain/user"; // Pure domain
export class TypeOrmUserRepository implements UserRepository {
async save(user: User): Promise<void> {
// Map Domain -> ORM
const ormEntity = new UserORM();
ormEntity.id = user.id;
ormEntity.email = user.email;
// Call Framework
await this.repository.save(ormEntity);
}
}
7. Validation & Governance
7.1 The "Source Code Dependency Rule"
Use a static analysis tool (like ArchUnit for Java, Dependency Cruiser for JS/TS, or NetArchTest for C#) to enforce that:
Domain imports nothing.
Application imports only Domain.
Infrastructure imports Application and Domain.
7.2 Testing Strategy
The primary benefit of this initiative is testability.
Unit Tests: Instantiate the Domain Entity directly. Run tests without spinning up a database or web server.
Integration Tests: Replace real Adapters with Mocks/Stubs (e.g., InMemoryUserRepository) to test the Application logic flow.
8. Deliverables Checklist
Directory structure separated by Domain, Application, and Infrastructure.
All Repository Interfaces extracted to Application/Ports.
Framework code moved to Infrastructure/Adapters.
CI Pipeline gate enforcing dependency direction rules.
Documentation on "How to add a new Feature" using the new pattern.