0Pricing
Clean Architecture & Design Patterns in Practice · 강의

웹 프레임워크에 적용하기

클린 아키텍처를 인기 웹 프레임워크(예: 스프링, ASP.NET, 장고)에 종속되지 않게 통합하는 전략을 배웁니다.

웹 프레임워크에 적용하기은(는) CoddyKit의 무료 Clean Architecture & Design Patterns in Practice 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clean Architecture & Design Patterns in Practice 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Frameworks & Clean Architecture

Web frameworks like Spring, Django, or ASP.NET are powerful tools for building applications. But how do they fit into a Clean Architecture?

The challenge is to leverage their features without letting them dictate or couple to our core business logic. This lesson explores strategies to achieve that separation.

Avoiding Framework Coupling

Coupling occurs when one part of your code is highly dependent on another. In Clean Architecture, we want our inner layers (Entities, Use Cases) to be independent.

  • If your Use Cases directly import Spring annotations or Django models, they are coupled.
  • This makes it hard to change frameworks, test core logic, or reuse components.

The Dependency Rule Applied

Remember the Dependency Rule? Dependencies can only flow inwards. This is crucial for framework integration.

  • Your core business logic (Entities, Use Cases) should never know about the web framework.
  • The web framework (an outer layer) can and should depend on your core logic.

We need a bridge that respects this rule.

Presenters & Adapters Bridge

The 'Frameworks & Drivers' layer is where our web framework lives. To communicate with the inner 'Interface Adapters' layer (which contains Presenters and Controllers), we use specific patterns:

  • Adapters: Translate incoming framework-specific requests into a format our Use Cases understand.
  • Presenters: Format the output from Use Cases into a structure suitable for the web framework's views or JSON responses.

The Web Controller as an Adapter

In web applications, the framework's controller often serves as the primary adapter. Its job is to:

  1. Receive HTTP requests (e.g., from a browser or API client).
  2. Extract relevant data from the request.
  3. Convert this data into a simple object (a Request Model) that matches the Use Case's Input Port.
  4. Call the Use Case.
  5. Receive output from the Use Case (a Response Model).
  6. Pass this output to a Presenter to format the final HTTP response.

Defining an Input Port

Our Use Cases expose simple interfaces, called Input Ports. The web controller will depend on this interface, not the concrete Use Case implementation. This keeps the Use Case truly independent.

Here's an example of an Input Port and its corresponding Request object:

interface AddItemInputPort {
    void execute(AddItemRequest request);
}

class AddItemRequest {
    public final String itemName;
    public final double price;

    public AddItemRequest(String itemName, double price) {
        this.itemName = itemName;
        this.price = price;
    }
}

public class Main {
    public static void main(String[] args) {
        // These are just definitions, not runnable logic on their own.
        // We'll see them in action soon!
        System.out.println("InputPort and Request defined.");
    }
}

Implementing a Use Case

The actual business logic resides within the Use Case. It implements the AddItemInputPort and performs the operation, completely unaware of how it was invoked (e.g., by a web request, a CLI, or a message queue).

interface AddItemInputPort {
    void execute(AddItemRequest request);
}

class AddItemRequest {
    public final String itemName;
    public final double price;

    public AddItemRequest(String itemName, double price) {
        this.itemName = itemName;
        this.price = price;
    }
}

class AddItemUseCase implements AddItemInputPort {
    @Override
    public void execute(AddItemRequest request) {
        System.out.println("Use Case: Processing item '" +
                           request.itemName + "' with price $" +
                           request.price + ".");
        // In a real application, this would involve business rules,
        // interacting with entities, and potentially repositories.
    }
}

public class Main {
    public static void main(String[] args) {
        AddItemInputPort useCase = new AddItemUseCase();
        AddItemRequest request = new AddItemRequest("Fancy Pen", 15.75);
        useCase.execute(request);
    }
}

Web Controller Adapter in Action

Now, let's see how a simplified web controller (acting as an adapter) uses our Use Case. Notice it only interacts with the AddItemInputPort interface, not the concrete AddItemUseCase class.

interface AddItemInputPort {
    void execute(AddItemRequest request);
}

class AddItemRequest {
    public final String itemName;
    public final double price;
    public AddItemRequest(String itemName, double price) {
        this.itemName = itemName;
        this.price = price;
    }
}

class AddItemUseCase implements AddItemInputPort {
    @Override
    public void execute(AddItemRequest request) {
        System.out.println("Use Case processed: " + request.itemName);
    }
}

// This class simulates a web framework controller
class WebFrameworkController {
    private final AddItemInputPort addItemInputPort;

    // Controller depends on the Input Port interface
    public WebFrameworkController(AddItemInputPort addItemInputPort) {
        this.addItemInputPort = addItemInputPort;
    }

    // This method simulates handling an HTTP POST request
    public String handleHttpRequest(String name, double cost) {
        System.out.println("Controller received HTTP request for: " + name);
        AddItemRequest request = new AddItemRequest(name, cost);
        addItemInputPort.execute(request); // Delegate to Use Case
        return "HTTP Response: Item '" + name + "' added.";
    }
}

public class Main {
    public static void main(String[] args) {
        // Setup: Inject the Use Case into the Controller
        AddItemInputPort useCase = new AddItemUseCase();
        WebFrameworkController controller = new WebFrameworkController(useCase);

        // Simulate an incoming web request
        String response = controller.handleHttpRequest("Notebook", 8.99);
        System.out.println(response);
    }
}

Benefits of Decoupling Frameworks

This adapter-based approach offers significant advantages:

  • Testability: Use Cases can be tested in isolation, without needing to boot up the entire web framework.
  • Maintainability: Changes or upgrades to your web framework have minimal impact on your core business logic.
  • Flexibility: You could swap out your web framework for another (e.g., from Spring to JAX-RS) with changes only in the outer 'Frameworks & Drivers' layer.
  • Framework Independence: Your valuable business rules are not tied to a specific technology vendor.

Check Your Understanding

Which of the following best describes the role of a web controller when integrating a Clean Architecture application with a web framework?

Recap: Framework Integration

In this lesson, we explored how to integrate web frameworks into a Clean Architecture application while maintaining crucial separation:

  • We treat the web framework as an outer layer that depends on our core logic, not the other way around.
  • Controllers in the web framework act as adapters, translating web requests into Use Case Input Ports and formatting Use Case output.
  • This approach ensures high testability, maintainability, and framework independence for your core application.

자주 묻는 질문

“웹 프레임워크에 적용하기” 강의는 무료인가요?

네 — “웹 프레임워크에 적용하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clean Architecture & Design Patterns in Practice 강의 전체를 잠금 해제할 수 있습니다. Clean Architecture & Design Patterns in Practice 강의에는 총 4개의 강의가 포함되어 있습니다.

“웹 프레임워크에 적용하기”에서 뭘 배우나요?

클린 아키텍처를 인기 웹 프레임워크(예: 스프링, ASP.NET, 장고)에 종속되지 않게 통합하는 전략을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Clean Architecture & Design Patterns in Practice을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Clean Architecture & Design Patterns in Practice을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Clean Architecture & Design Patterns in Practice은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“웹 프레임워크에 적용하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Clean Architecture & Design Patterns in Practice 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Clean Architecture & Design Patterns in Practice 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 프레젠터와 뷰 모델
  2. 웹 프레임워크에 적용하기
  3. 프레젠테이션 계층 테스트
  4. 겸손한 객체와 뷰의 경계
← Clean Architecture & Design Patterns in Practice(으)로 돌아가기