Skip to content
Back to blog
Architecture

Layered Architecture: Beyond Separating Code into Layers

Updated 25 min read

Layered Architecture is more than separating code into controllers, services, and repositories. Learn how to define responsibilities, manage dependencies, avoid common design mistakes, and build software that is easier to test, maintain, and evolve.

Table of Contents

Introduction

When developers first learn about Layered Architecture, they are often taught to divide an application into three or four layers: Presentation, Business Logic, and Data Access.

The explanation sounds straightforward: each layer has a specific responsibility, and the layers communicate with one another through well-defined boundaries.

But having multiple layers does not automatically make an application well-architected.

A codebase can have separate controllers, services, repositories, and models while still suffering from tightly coupled components, duplicated business rules, difficult testing, and changes that ripple throughout the system.

For example, a business rule might be implemented in a controller today, duplicated in a background job tomorrow, and copied into another service next month. Every component appears to have its own place, yet no single component clearly owns the rule.

The problem is not the absence of layers. It is the absence of clear responsibilities and controlled dependencies.

Layered Architecture addresses this problem by organizing an application into logical layers, each responsible for a distinct part of the system. The goal is to make changes more predictable, isolate implementation details, and give developers a clearer understanding of where different responsibilities belong.

However, these benefits depend on how the layers are designed and how they interact.

The deeper idea behind Layered Architecture is not to organize files into folders. It is to manage complexity by establishing boundaries between different kinds of responsibility.

This article explores that idea through practical examples, common design mistakes, and the trade-offs involved in applying Layered Architecture.


1. From Tangled Code to Layered Architecture

The problem: Everything depends on everything

Consider a simple order-processing endpoint in a web application.

When a customer places an order, the application needs to:

  1. Receive and validate the HTTP request.
  2. Retrieve the requested products.
  3. Check whether the products are available.
  4. Calculate the total price.
  5. Create the order.
  6. Save the order to the database.
  7. Return an HTTP response.

Without clear boundaries, all these responsibilities can end up in a single controller.

java
@PostMapping("/orders")
public ResponseEntity<?> createOrder(
        @RequestBody CreateOrderRequest request) {

    Connection connection = DriverManager.getConnection(
        "jdbc:postgresql://localhost:5432/shop",
        "user",
        "password"
    );

    double total = 0;

    for (OrderItemRequest item : request.items()) {
        PreparedStatement statement = connection.prepareStatement(
            "SELECT price, stock FROM products WHERE id = ?"
        );

        statement.setLong(1, item.productId());

        ResultSet result = statement.executeQuery();

        if (!result.next()) {
            return ResponseEntity.badRequest()
                .body("Product not found");
        }

        if (result.getInt("stock") < item.quantity()) {
            return ResponseEntity.badRequest()
                .body("Insufficient stock");
        }

        total += result.getDouble("price") * item.quantity();
    }

    // Insert order into the database.
    // Update product inventory.
    // Build and return the response.

    return ResponseEntity.ok(total);
}

This is a simplified illustration, but it demonstrates several problems.

  • Mixed responsibilities: The controller handles HTTP, business rules, SQL, and persistence.
  • Tight coupling: Business logic depends directly on JDBC and the database schema.
  • Difficult testing: Testing the order rules requires dealing with database connections and HTTP-related code.
  • Poor reuse: A scheduled job or message consumer cannot easily reuse the same order-processing logic without duplicating it or calling the controller indirectly.
  • Fragile changes: Changing the database implementation or the way requests are handled can affect unrelated logic.

The issue is not that the controller is long. The deeper issue is that different concerns have been combined into one component.

The solution: Separate responsibilities into layers

Layered Architecture separates these responsibilities into logical groups.

A conventional structure might look like this:

text
Presentation Layer
        |
        v
Application / Service Layer
        |
        v
Domain / Business Layer
        |
        v
Data Access / Infrastructure Layer
        |
        v
Database

This diagram illustrates one possible arrangement, not a universal requirement. Some applications combine the Application and Domain layers, while others use a three-layer structure with a single Business Layer.

The important distinction is what each layer is responsible for, rather than how many layers exist.

For example:

  • The Presentation Layer handles HTTP requests and responses.
  • The Application Layer coordinates the order-creation use case.
  • The Domain Layer enforces business rules about orders and order items.
  • The Infrastructure Layer implements database access and other external integrations.

Now, changing the HTTP framework should not require rewriting the rules that determine whether an order is valid.

Likewise, changing the database implementation should not require moving business rules into a different layer.

This separation is the foundation of Layered Architecture.


2. What Problem Does Layered Architecture Actually Solve?

Layered Architecture is often described as a way to separate concerns. That is correct, but the phrase becomes more useful when we examine the specific problems it addresses.

2.1 Separation of Concerns

Different parts of an application solve different kinds of problems.

An HTTP controller deals with routing, request parsing, status codes, and response serialization. A business component determines whether an operation is allowed. A repository deals with retrieving and storing data.

These concerns may participate in the same use case, but they do not need to be implemented in the same component.

Separating them makes each component easier to understand because its purpose is more narrowly defined.

For example, an order controller should not need to know how inventory is stored in PostgreSQL. It only needs to receive a request and invoke the appropriate application operation.

The benefit is not merely cleaner code. It reduces the number of unrelated concepts a developer must understand when changing one part of the application.

2.2 Managing Dependencies

Separation alone is insufficient if every component still depends directly on every other component.

Imagine that the order-processing logic directly creates JDBC connections, constructs HTTP responses, and reads framework-specific request objects.

Even if that logic lives in a class named OrderService, it remains coupled to several implementation details.

A well-designed layered system limits which components can depend on which other components.

The application layer should not need to understand HTTP serialization. The domain model should not need to know which database stores its data.

These restrictions reduce the number of places that must change when an implementation detail changes.

2.3 Isolating Changes

Suppose the application initially uses PostgreSQL and later needs to use another relational database.

If database-specific SQL and connection handling are isolated in the infrastructure layer, most business logic can remain unchanged.

Similarly, if a REST API is replaced by a message consumer, the new entry point can invoke the same application use case without reproducing the order-processing rules.

This does not mean that changing infrastructure will never affect other layers. Differences in transactions, data types, query behavior, and consistency guarantees can still matter.

The objective is to minimize the impact of changes by keeping implementation-specific responsibilities behind appropriate boundaries.

2.4 Improving Testability

Layered Architecture can make testing easier by allowing different parts of the application to be tested at different levels.

For example:

  • Domain tests verify business rules without starting a web server or database.
  • Application tests verify use-case coordination using controlled dependencies.
  • Repository integration tests verify actual database behavior.
  • API tests verify HTTP contracts and request handling.

Each test focuses on the behavior of the component under examination.

This does not eliminate the need for integration tests. A component may work correctly in isolation while the complete system fails because of incorrect wiring, transaction boundaries, or database behavior.

The value of layering is that it gives us more control over what a test needs to initialize and what it needs to verify.


3. Understanding the Layers

There is no single layer structure that every application must follow. The exact boundaries depend on the application's complexity and business requirements.

For a typical business application, four logical responsibilities are useful to distinguish.

3.1 Presentation Layer

The Presentation Layer is the entry point through which external users or systems interact with the application.

In a web application, it commonly includes controllers, route handlers, request DTOs, response DTOs, and HTTP-specific validation.

Its responsibilities include:

  • Receiving and parsing requests.
  • Validating request structure and input formats.
  • Translating requests into application commands or queries.
  • Invoking the appropriate application operation.
  • Translating results and errors into HTTP responses.

For example:

java
@RestController
@RequestMapping("/orders")
public class OrderController {

    private final CreateOrderService createOrderService;

    public OrderController(
            CreateOrderService createOrderService) {
        this.createOrderService = createOrderService;
    }

    @PostMapping
    public ResponseEntity<OrderResponse> createOrder(
            @RequestBody CreateOrderRequest request) {

        OrderResult result = createOrderService.execute(
            request.customerId(),
            request.items()
        );

        return ResponseEntity.ok(
            new OrderResponse(result.orderId(), result.total())
        );
    }
}

The controller translates an HTTP request into an application operation and translates the result back into an HTTP response.

It does not calculate prices, manage inventory, or execute SQL directly.

A controller may perform input validation, but it should not become the sole authority for business rules that must remain true regardless of how an operation is invoked.

For example, checking that quantity is a positive integer is useful request validation. Ensuring that an order cannot contain an invalid quantity is a business invariant that must also be protected by the relevant domain or application logic.

The Presentation Layer should understand how the application is accessed, not how every business operation is implemented.

3.2 Application / Service Layer

The Application Layer coordinates use cases.

It determines which operations must happen, in what sequence, and which components are needed to complete a particular application request.

For order creation, this may involve:

  1. Retrieving the relevant customer and product information.
  2. Constructing an order.
  3. Applying domain operations.
  4. Persisting the order.
  5. Returning a result to the caller.

A simplified example:

java
public class CreateOrderService {

    private final ProductRepository productRepository;
    private final OrderRepository orderRepository;

    public CreateOrderService(
            ProductRepository productRepository,
            OrderRepository orderRepository) {
        this.productRepository = productRepository;
        this.orderRepository = orderRepository;
    }

    public OrderResult execute(
            Long customerId,
            List<OrderItemRequest> items) {

        Order order = Order.create(customerId);

        for (OrderItemRequest item : items) {
            Product product = productRepository
                .findById(item.productId())
                .orElseThrow(
                    () -> new IllegalArgumentException(
                        "Product not found"
                    )
                );

            order.addItem(product, item.quantity());
        }

        orderRepository.save(order);

        return new OrderResult(
            order.getId(),
            order.getTotal()
        );
    }
}

This example is illustrative. A production implementation would need to consider transactions, concurrent inventory changes, error types, and the persistence lifecycle of newly created orders.

Notice that the service coordinates the use case but does not contain SQL statements or HTTP response construction.

It delegates product retrieval to a repository and order-related rules to the Order domain object.

However, a Service class is not automatically the correct owner of every business rule.

Some rules belong to individual domain objects. Other rules coordinate several objects or depend on external services and therefore belong in application or domain services.

The correct placement depends on the responsibility being enforced, not simply on whether the code is labeled business logic.

3.3 Domain / Business Layer

The Domain Layer represents the business concepts, rules, and constraints that define the application.

In an order-processing system, these concepts may include:

  • Orders.
  • Order items.
  • Product prices.
  • Order totals.
  • Order statuses.
  • Rules governing whether an order can be modified or cancelled.

Consider an order that must never contain a zero or negative quantity.

java
public class OrderItem {

    private final Long productId;
    private final BigDecimal unitPrice;
    private final int quantity;

    public OrderItem(
            Long productId,
            BigDecimal unitPrice,
            int quantity) {

        if (quantity <= 0) {
            throw new IllegalArgumentException(
                "Quantity must be positive"
            );
        }

        if (unitPrice.signum() < 0) {
            throw new IllegalArgumentException(
                "Unit price cannot be negative"
            );
        }

        this.productId = productId;
        this.unitPrice = unitPrice;
        this.quantity = quantity;
    }

    public BigDecimal getSubtotal() {
        return unitPrice.multiply(
            BigDecimal.valueOf(quantity)
        );
    }
}

The object protects the conditions that must hold for a valid order item.

A controller, scheduled task, message consumer, or application service can all construct an OrderItem. None of them should be able to bypass the constructor's rules simply because they use a different entry point.

This is where Layered Architecture connects naturally with object-oriented design: the architecture determines the broad boundaries of responsibility, while object design determines which objects own and enforce particular rules.

Not every application needs a sophisticated Domain Layer. A simple CRUD application may have very little domain behavior. In that case, introducing many domain classes can create unnecessary complexity.

But when business rules become important, keeping them separate from HTTP and persistence concerns helps prevent those rules from being duplicated across the application.

3.4 Infrastructure / Data Access Layer

The Infrastructure Layer contains implementation details for interacting with external systems.

Depending on the application, it may include:

  • Database repositories.
  • SQL queries and ORM mappings.
  • Message queue producers and consumers.
  • Email providers.
  • File storage.
  • Third-party API clients.

Consider a repository contract:

java
public interface OrderRepository {

    void save(Order order);

    Optional<Order> findById(Long orderId);
}

The application code depends on the operations it needs, rather than directly depending on SQL statements or a specific database connection.

An infrastructure implementation can provide the actual persistence behavior:

java
public class PostgresOrderRepository
        implements OrderRepository {

    @Override
    public void save(Order order) {
        // Persist the order using PostgreSQL.
    }

    @Override
    public Optional<Order> findById(Long orderId) {
        // Query PostgreSQL and map the result.
        return Optional.empty();
    }
}

The implementation above omits the actual persistence code for brevity.

The important point is that the repository contract expresses what the application needs, while the infrastructure implementation determines how that capability is provided.

A repository interface is not mandatory for every database operation. If the application is small and the additional abstraction offers no meaningful benefit, a simpler design may be preferable.

Infrastructure should provide technical capabilities to the application, rather than becoming the place where unrelated business rules accumulate.


4. Dependency Rules — The Most Important Part

Understanding the responsibilities of individual layers is only half of the problem. The other half is understanding how they depend on one another.

4.1 Call direction and dependency direction are not always the same

In a conventional layered application, requests commonly flow from the Presentation Layer toward the business and data access layers.

For example:

text
HTTP Request
     |
     v
OrderController
     |
     v
CreateOrderService
     |
     v
OrderRepository
     |
     v
PostgreSQL

This represents the runtime call flow.

But the source-code dependency structure can be more subtle.

If CreateOrderService directly constructs a PostgresOrderRepository, the application layer becomes dependent on a particular database implementation.

java
public class CreateOrderService {

    private final PostgresOrderRepository repository;

    public CreateOrderService() {
        this.repository = new PostgresOrderRepository();
    }
}

Now the service knows not only what it needs to do, but also which concrete implementation must provide persistence.

Replacing that implementation may require changing the service itself.

Dependency injection improves the situation:

java
public class CreateOrderService {

    private final OrderRepository repository;

    public CreateOrderService(OrderRepository repository) {
        this.repository = repository;
    }
}

The service depends on a contract rather than a concrete PostgreSQL class.

The application can receive a PostgresOrderRepository at runtime without needing to instantiate that class itself.

This reduces coupling, but an important distinction remains: dependency injection and Dependency Inversion are related, not identical. Passing an implementation into a constructor is useful, but the dependency structure must also be designed so that high-level policy does not become unnecessarily tied to low-level implementation details.

4.2 Layered Architecture does not automatically imply Dependency Inversion

A traditional layered architecture often allows higher layers to depend on lower layers.

For example, a business service may directly import a concrete repository class. The code is still divided into layers, but the dependency structure is less flexible.

Dependency Inversion Principle (DIP) introduces a stronger design rule: high-level policy and low-level implementation should depend on appropriate abstractions rather than the high-level policy depending directly on implementation details.

One way to achieve this is to define an application-owned repository contract and implement it in the infrastructure layer.

text
Application Layer
       |
       v
OrderRepository (contract)
       ^
       |
PostgresOrderRepository
(Infrastructure Layer)

The application invokes the contract, and the infrastructure implementation satisfies it.

The source-code dependency points toward the abstraction, even though the runtime call eventually reaches the concrete implementation.

This design is particularly useful when database independence, isolated application testing, or alternative infrastructure implementations provide real value.

It is not necessary to introduce an interface for every class. An abstraction should represent a meaningful boundary, not merely add another file to the project.

4.3 Dependency leakage

A common architectural problem occurs when implementation details from one layer spread into another.

For example, suppose the domain model directly imports Spring framework annotations, HTTP request classes, or database-specific persistence types.

java
public class Order {

    private Long id;

    // Business state and behavior
}

The class above is framework-independent. If it later needs to be used by a command-line application or a message consumer, it does not need to understand a new delivery mechanism.

By contrast, if the domain model depends directly on an HTTP request object, it becomes harder to reuse without carrying the assumptions of the web layer.

The same issue occurs when business rules are expressed in SQL queries or database triggers that the application layer does not account for.

Some rules genuinely belong in the database, particularly constraints that protect data integrity across concurrent operations. The goal is not to prohibit all database-level rules. It is to ensure that critical business behavior remains explicit, consistent, and correctly enforced across the system.

The architectural question is:

Does this component depend on an implementation detail that it should not need to know about?

That question is often more useful than simply checking whether a class lives in the correct package.


5. A Practical Example: Building an Order System

The previous sections introduced the layers independently. Now consider how they work together in a complete use case.

Suppose a customer places an order containing two products.

The application needs to validate the request, retrieve product information, construct the order, calculate its total, and save it.

Step 1: The Presentation Layer receives the request

The controller receives the HTTP request and converts it into the input expected by the application.

It should not need to know the SQL schema or calculate every order subtotal itself.

Step 2: The Application Layer coordinates the use case

The application service retrieves the information needed to create the order and coordinates the operation.

It may also establish a transaction boundary, depending on the framework and persistence design.

Step 3: The Domain Layer enforces business rules

The domain objects validate their own invariants and calculate values based on their state.

For example, an order item rejects an invalid quantity, while an order calculates its total from its items.

Step 4: The Infrastructure Layer persists the result

The repository implementation stores the order using the selected persistence technology.

The application layer does not need to embed PostgreSQL-specific SQL in the use case.

Step 5: The result returns to the caller

The application returns a result containing the order identifier and relevant calculated values.

The controller converts that result into an HTTP response.

The overall flow is:

text
Client
  |
  v
OrderController
  |
  v
CreateOrderService
  |
  +-----> ProductRepository
  |              |
  |              v
  |         Product Storage
  |
  v
Order Domain Model
  |
  v
OrderRepository
  |
  v
PostgreSQL

This diagram simplifies the architecture. In a real application, repository contracts, transaction management, inventory reservation, and payment processing may introduce additional components.

The important point is that each component contributes a distinct responsibility to the use case.

What happens when requirements change?

Consider three changes.

Change A: The application introduces a message-based entry point.

A message consumer can invoke the same application service without duplicating the business rules or pretending that a message is an HTTP request.

Change B: The database implementation changes.

The repository implementation may need to change, but the application service can remain unchanged if the new implementation satisfies the existing contract and preserves the required behavior.

Change C: The business introduces a new order rule.

The rule should be added to the component responsible for maintaining that invariant. If it concerns the validity of an individual order, the domain model may be the right place. If it coordinates several services or objects, the application or domain service may be more appropriate.

These examples illustrate the real value of separating concerns: each change has a more predictable place to begin.

However, boundaries do not eliminate all change propagation. If a new requirement changes the meaning of a repository contract or the public behavior of a use case, multiple components may legitimately need updates.

Good architecture makes those dependencies explicit rather than pretending that changes can always be isolated completely.


6. Common Misconceptions

6.1 More layers mean better architecture

A common mistake is creating a controller, service, manager, helper, processor, repository, and several interfaces for every feature, regardless of complexity.

Consider a simple operation that retrieves a product:

text
Controller
    |
    v
ProductService
    |
    v
ProductRepository
    |
    v
Database

This may be a reasonable structure for a growing application. But if every component merely forwards the same arguments to the next component, the additional layers may contribute little value.

The purpose of layering is to separate responsibilities, not maximize the number of classes.

A useful layer introduces a meaningful boundary, policy, or capability. A pass-through layer that has no independent responsibility should be questioned.

6.2 The Service Layer must contain all business logic

The word "service" is often used too broadly.

Some services coordinate use cases. Others implement domain operations that naturally span multiple objects. Some classes named Service are little more than wrappers around database calls.

A domain object can enforce a rule about its own state, while an application service coordinates the broader workflow.

For example, an Order object can ensure that an order cannot be cancelled after shipment. An application service can coordinate loading the order, invoking the cancellation operation, and saving the result.

Neither component needs to own every responsibility.

The correct design depends on the nature of the rule and the consistency guarantees required by the system.

6.3 Repository interfaces are always necessary

An interface can make an implementation replaceable and simplify isolated testing. But creating an interface for every repository or helper without a real need can add unnecessary complexity.

An interface is especially valuable when it defines a meaningful boundary between application policy and infrastructure, or when multiple implementations genuinely need to be supported.

If a small application has no meaningful need for interchangeable implementations, a concrete class may be sufficient.

The goal is not to maximize abstraction. It is to use abstraction where it reduces coupling or clarifies responsibility.

6.4 Layered Architecture is the same as Clean Architecture

These architectures are related, but they are not interchangeable terms.

Traditional Layered Architecture commonly organizes code into horizontal layers, with higher layers calling lower layers.

Clean Architecture emphasizes dependency rules that keep business policies independent of frameworks and external mechanisms.

A traditional layered application can depend directly on database-specific implementations. A Clean Architecture-style design generally places abstractions so that the inner policy layers do not depend on those outer implementation details.

A layered system can adopt Dependency Inversion and become more independent of infrastructure, but simply having Presentation, Service, and Repository packages does not guarantee this.

6.5 A domain model must always contain complex behavior

Not every application needs a rich domain model.

A reporting application, a straightforward CRUD system, or a data pipeline may primarily transform and transport data. In such cases, separating data from behavior can be an intentional and reasonable choice.

The problem arises when important business invariants are scattered across controllers, services, batch jobs, and helper classes with no clear owner.

A domain model should have meaningful responsibilities when the business domain requires them. It should not be made artificially complex just to satisfy an architectural template.


7. The Cost of Layered Architecture

Layered Architecture introduces useful boundaries, but those boundaries also have costs.

7.1 Boilerplate and indirection

Every additional layer can introduce another class, interface, mapping operation, or method call.

For a simple feature, the overhead may exceed the complexity it removes.

Developers should ask whether a new abstraction provides a useful boundary or merely moves code somewhere else.

7.2 Pass-through layers

A pass-through layer forwards requests without making decisions, enforcing rules, or providing a meaningful abstraction.

One pass-through component may be harmless. A codebase full of them can make simple operations difficult to trace.

Not every forwarding method is unnecessary, though. A layer may provide a stable API, a transaction boundary, authorization, or future extension point even when its current implementation is small.

The important question is whether the boundary serves a clear purpose.

7.3 Anemic domain models

A domain model can become a collection of fields, getters, setters, and persistence annotations, while all business rules live in services.

This is not automatically wrong. Some architectures intentionally separate data from behavior.

However, when domain invariants must always hold, scattering their enforcement across services makes it easier for one entry point to forget a validation step.

For example, if the rule that an order cannot be cancelled after shipment exists only in one controller or service, another workflow may accidentally bypass it.

When an invariant belongs to the order itself, the order should expose operations that enforce it rather than allowing arbitrary state changes.

7.4 False confidence about transactions and concurrency

Separating code into layers does not guarantee data consistency.

Suppose two requests attempt to purchase the final unit of a product simultaneously. Both requests might read the same available stock before either updates it.

Even with separate services and repositories, the application can still oversell inventory unless the persistence operations and transaction strategy protect against the race condition.

Depending on the requirements, this may involve database constraints, atomic updates, locking, transaction isolation, or a reservation mechanism.

Similarly, saving an order and charging a payment provider are not automatically one atomic transaction simply because the operations are invoked from the same service.

Architecture must account for consistency boundaries and failure modes, not only class boundaries.

7.5 Premature abstraction

Designing every component for hypothetical future implementations can create more complexity than it removes.

An interface for a single implementation is not inherently bad. The question is whether it represents a valuable contract or merely anticipates a change that may never occur.

A practical approach is to establish clear responsibilities first, introduce abstractions at meaningful boundaries, and refine the architecture as actual requirements justify it.

Good architecture minimizes accidental coupling without replacing every concrete dependency with an abstraction.


8. When Should You Use Layered Architecture?

Layered Architecture is a useful default for many business applications because it offers a clear way to organize request handling, application workflows, domain behavior, and infrastructure.

It is particularly appropriate when:

  • The application contains multiple business use cases.
  • Business rules need to be tested independently of HTTP and persistence.
  • Several entry points must reuse the same application operations.
  • Database and external service integrations are likely to evolve.
  • Multiple developers need consistent boundaries for organizing their work.

However, the amount of separation should match the problem.

Small CRUD applications

A lightweight structure may be sufficient:

text
Controller
    |
    v
Service
    |
    v
Repository

If business behavior is minimal, a separate domain layer may add little value.

Applications with growing business complexity

More explicit boundaries become useful:

text
Presentation
    |
    v
Application
    |
    v
Domain
    ^
    |
Infrastructure

In this design, the application layer coordinates use cases, the domain owns relevant business rules, and infrastructure implements external capabilities through suitable contracts.

The exact dependency structure depends on the architectural style being used.

Systems with specialized architectural requirements

Some systems benefit from alternatives or extensions, such as:

  • Hexagonal Architecture: emphasizes ports and adapters around application capabilities.
  • Clean Architecture: emphasizes keeping inner business policies independent of outer implementation details.
  • Modular Monolith: emphasizes module boundaries and controlled dependencies within a single deployable application.
  • Event-Driven Architecture: emphasizes asynchronous communication and event-based workflows.

These approaches can coexist with layered organization. They address different architectural concerns rather than serving as mutually exclusive replacements in every situation.

The right choice depends on the problem the architecture needs to solve.


Summary

ConceptCore PurposeCommon Misconception
Presentation LayerHandles external interaction and translates requests and responsesIt should contain all validation and business rules
Application LayerCoordinates use cases and application workflowsEvery business rule belongs in a service
Domain LayerModels business concepts and enforces relevant invariantsEvery application needs a rich domain model
Infrastructure LayerImplements persistence and external integrationsAll business logic belongs in repositories
Dependency boundariesControl coupling between responsibilitiesSeparate packages automatically create loose coupling
AbstractionHides implementation details behind meaningful contractsEvery class needs an interface
Layered ArchitectureOrganizes responsibilities into logical boundariesMore layers automatically mean better design

Layered Architecture provides a practical foundation for organizing software, but its value does not come from the number of layers or the names of the packages.

The deeper question is whether each component has a clear responsibility, whether business rules are enforced consistently, and whether dependencies make changes more predictable or more difficult.

A well-designed layered application does not eliminate complexity. It gives that complexity a structure that developers can understand, test, and evolve.

This is also where Layered Architecture connects to object-oriented design. OOP helps determine which objects should own state, behavior, and invariants. Layered Architecture helps organize those objects and other components into larger boundaries with controlled dependencies.

The goal is not to put every class in the correct folder. The goal is to make responsibility clear, dependency intentional, and change manageable.

To go deeper: SOLID Principles, Dependency Inversion, Clean Architecture, Hexagonal Architecture, and Domain-Driven Design (DDD).

  • Architecture
  • Programing
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 22 min read

Design Patterns: Beyond the Definitions

Design patterns are more than reusable code structures. Learn the problems they solve, the trade-offs they introduce, and how to decide when a pattern improves your software design—and when a simpler solution is better.

Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.