The 3-Layer Rule: Cut Redundant Layers for Faster Delivery

In enterprise software development, there is a dangerous tendency to confuse indirection with architecture.

We’ve all inherited the classic corporate codebase: a system built with the best of intentions, designed to look like the diagrams from an enterprise patterns textbook. It boasts an abundance of folders, dozens of project assemblies, and an impenetrable web of abstractions.

Yet, when you trace a simple user request—such as updating a customer’s postal address or opening a savings account—you discover a grim reality:

HTTP POST /api/customer/address
  └── CustomerController
        └── CustomerFacade
              └── CustomerApplicationService
                    └── ICustomerDomainService -> CustomerDomainService
                          └── ICustomerRepository -> CustomerRepository
                                └── CustomerDbContext
                                      └── Database

Seven files. Five project boundaries. Four separate mapping steps that convert CustomerAddressRequest to CustomerAddressDto to CustomerAddressCommand to CustomerAddressEntity.

And what did the intermediate layers actually do?

Absolutely nothing.

No business rules were evaluated. No state was calculated. No security decisions were made. Data merely entered at the top and was handed down through a bucket brigade of pass-through classes until it hit the database.

This is the Pass-Through Onion: an over-engineered maze that masquerades as clean architecture while actively destroying developer velocity and code clarity.


1. The Enterprise Myth: “More Layers = More Scalable”

Teams usually adopt deep N-tier architectures because of hypothetical future requirements:

  • “What if we need to swap out Entity Framework for Dapper or Cosmos DB tomorrow?”
  • “What if our web frontend is replaced by a desktop application or an IoT service?”
  • “What if we need to unit-test every single layer in complete isolation?”

In twenty years of enterprise software engineering, the number of times a production application swaps its database provider mid-lifecycle without rewriting the entire data access layer is virtually zero.

Yet squads pay a recurring, daily tax for that hypothetical scenario:

  1. The Cognitive Tax: Fixing a validation bug or adding a single database column requires opening eight tabs across eight folders (/Controllers, /Services, /Interfaces, /Repositories, /DTOs, /Entities, /Mappers). The structure obscures domain logic rather than clarifying it.
  2. The 1-to-1 Interface Lie: Developers create ICustomerService with only ever one concrete class: CustomerService. The interface exists solely because a mocking library or a tutorial demanded it, adding indirection without delivering actual polymorphism.
  3. The Copy-Paste Trap: Faced with heavy ceremony and tight deadlines, time-pressured developers stop trying to understand the architectural flow. They locate an existing endpoint, duplicate all seven layers, rename the DTO properties, and push it to production.

2. Code Contrast: The Onion vs. The Reality

Consider an endpoint that retrieves an active account balance in a .NET application.

The Over-Abstracted Pass-Through (The Anti-Pattern)

// 1. Controller
[HttpGet("{id}/balance")]
public async Task<IActionResult> GetBalance(int id) {
    var dto = await _facade.GetAccountBalanceAsync(id);
    return Ok(new AccountBalanceResponse(dto.Balance));
}

// 2. Facade
public async Task<AccountBalanceDto> GetAccountBalanceAsync(int id) =>
    await _accountAppService.GetAccountBalanceAsync(id);

// 3. Application Service
public async Task<AccountBalanceDto> GetAccountBalanceAsync(int id) =>
    await _accountDomainService.GetBalanceAsync(id);

// 4. Domain Service
public async Task<AccountBalanceDto> GetBalanceAsync(int id) {
    var entity = await _accountRepository.GetByIdAsync(id);
    return new AccountBalanceDto { Balance = entity.Balance };
}

// 5. Repository
public async Task<Account> GetByIdAsync(int id) =>
    await _dbContext.Accounts.FindAsync(id);

Every single layer is boilerplate plumbing. If a requirement changes, you have to modify and recompile five files across multiple projects.

The Resilient Baseline: Feature-First (Vertical Slice)

If data doesn’t transform across layers, collapse the layers. In modern .NET (via Razor Pages or Minimal APIs), the exact same operation can be clean, direct, and completely testable in a single place:

// Features/Accounts/GetAccountBalance.cs
public static class GetAccountBalanceEndpoint
{
    public static void Map(IEndpointRouteBuilder app)
    {
        app.MapGet("/api/accounts/{id:int}/balance", async (int id, AppDbContext db) =>
        {
            var balance = await db.Accounts
                .Where(a => a.Id == id && a.IsActive)
                .Select(a => (decimal?)a.Balance)
                .FirstOrDefaultAsync();

            return balance is not null 
                ? Results.Ok(new { Balance = balance.Value }) 
                : Results.NotFound();
        });
    }
}

The intent is immediately obvious. The query is optimized directly at the database boundary (selecting only the column required). There are no orphan DTOs or redundant interfaces cluttering the solution tree.


3. The 3-Layer Rule

To keep architecture sustainable, enforce the 3-Layer Rule across squad code reviews:

The 3-Layer Rule: If an object or payload travels through three consecutive layers without any validation, business calculation, or protocol transformation, delete the intermediate layers.

If a controller or PageModel is simply taking an ID and passing it to a service that passes it to a repository that calls DbSet.Find(), your service and repository are useless overhead. Call the database context directly.


4. Vertical Slices Over Horizontal Strata

Instead of organizing software by technical mechanics (grouping all controllers together, all repositories together, all DTOs together), organize by business capabilities:

Features/
└── SavingsAccountApplication/
    ├── SubmitApplication.cshtml
    ├── SubmitApplication.cshtml.cs    <-- UI handling & validation
    ├── ApplicationValidator.cs        <-- Domain constraints
    └── ExperianCreditCheckClient.cs   <-- Genuine external boundary

The Benefits:

  • High Cohesion: Everything required to understand, debug, or extend the Savings Account Application lives in one folder.
  • Low Coupling: Modifying the savings account journey will never introduce a regression in the current account journey.
  • Effortless Pruning: When a feature is deprecated or replaced, you delete the directory. You don’t have to hunt down zombie DTOs and unused repository methods scattered across three assemblies.

5. When to Introduce Abstractions (The Rule of Three)

Simplicity does not mean avoiding abstractions; it means earning them. Only introduce an interface or layer under three conditions:

  1. Genuine External Boundaries: Third-party vendor APIs (e.g., credit reference agencies, payment gateways, messaging brokers) where contracts can drift or network calls must be mocked.
  2. True Polymorphism: When there are at least two distinct, active runtime implementations (not one real class and one mock class).
  3. Complex Domain Rules: High-value business logic that requires unit testing without database or HTTP plumbing attached.

Architecture Through Subtraction

True architectural maturity isn’t proven by how many abstractions you can layer onto a codebase. Anyone can build a fragile tower of pass-through classes; it takes discernment and discipline to keep a system lean.

Stop building software for hypothetical futures that never arrive. Peel back the pass-through onion, collapse the redundant layers, and let simplicity carry the weight of your system.

Leave a Reply

Your email address will not be published. Required fields are marked *