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

사용 사례(인터랙터) 구현

엔터티를 조율해 애플리케이션의 특정 기능을 수행하고 애플리케이션에 특화된 비즈니스 규칙을 구현하는 사용 사례를 개발합니다.

사용 사례(인터랙터) 구현은(는) 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개의 강의가 포함되어 있습니다.

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

What are Use Cases (Interactors)?

In Clean Architecture, Use Cases (sometimes called Interactors) are at the heart of your application's logic. They represent the specific tasks or features your application can perform.

Think of them as the orchestrators of your core business entities. They define how your application uses those entities to achieve a goal, like 'create a new user' or 'process an order'.

Role of Use Cases in Clean Architecture

Use Cases sit in the 'Use Cases' layer, just outside the 'Entities' layer. This means:

  • They depend on Entities.
  • They do NOT depend on external layers like the UI, databases, or web frameworks.

Their main job is to coordinate the flow of data to and from the Entities and direct the Entities to perform their specific business rules.

Embodying Application Rules

While Entities hold the enterprise-wide business rules (rules true for the entire business, regardless of application), Use Cases embody application-specific business rules.

For example, an 'Order' Entity might have a rule that an order total cannot be negative. A 'Process Order' Use Case might have an application rule that a user must be logged in to place an order, or that certain promotions apply at checkout.

Defining Use Case Boundaries

To keep Use Cases isolated, they communicate with the outside world through interfaces:

  • Input Port: An interface that defines what data a Use Case expects to receive.
  • Output Port: An interface that defines what data a Use Case will produce.

These ports ensure the Use Case doesn't know about specific UI components or database implementations.

Anatomy of a Use Case

A typical Use Case is a class with a single public method (e.g., execute or handle). This method usually takes an 'Input Data Transfer Object' (DTO) and returns an 'Output DTO'.

Inside, it interacts with entities and often uses 'Gateway' or 'Repository' interfaces to talk to data storage or external services, without knowing their concrete implementations.

Example: Create User Use Case

Let's consider a CreateUserUseCase. First, we define the simple data structures for input and output. These are plain Java objects (POJOs).

public class CreateUserInput {
  public String name;
  public String email;
}

public class CreateUserOutput {
  public String userId;
  public String message;
  public boolean success;
}

Implementing the Logic

Now, let's see how the CreateUserUseCase orchestrates a User entity and interacts with a UserRepository (an interface) to perform its task.

Try running this example:

public class User {
  private String id;
  private String name;
  private String email;

  public User(String id, String name, String email) {
    this.id = id;
    this.name = name;
    this.email = email;
  }

  public String getId() { return id; }
  public String getName() { return name; }
  public String getEmail() { return email; }
  
  public boolean isValid() { return name != null && !name.isEmpty() && email != null && email.contains("@"); }
}

interface IUserRepository {
  void save(User user);
  String generateId();
}

class InMemoryUserRepository implements IUserRepository {
  @Override
  public void save(User user) {
    System.out.println("Saving user: " + user.getName() + " with ID: " + user.getId());
  }

  @Override
  public String generateId() {
    return "user-" + System.currentTimeMillis();
  }
}

public class CreateUserInput {
  public String name;
  public String email;
}

public class CreateUserOutput {
  public String userId;
  public String message;
  public boolean success;
}

class CreateUserUseCase {
  private final IUserRepository userRepository;

  public CreateUserUseCase(IUserRepository userRepository) {
    this.userRepository = userRepository;
  }

  public CreateUserOutput execute(CreateUserInput input) {
    CreateUserOutput output = new CreateUserOutput();

    if (input.name == null || input.name.isEmpty()) {
      output.success = false;
      output.message = "Name cannot be empty.";
      return output;
    }
    if (input.email == null || !input.email.contains("@")) {
      output.success = false;
      output.message = "Invalid email address.";
      return output;
    }

    String newId = userRepository.generateId();
    User newUser = new User(newId, input.name, input.email);

    if (!newUser.isValid()) {
      output.success = false;
      output.message = "User data is invalid.";
      return output;
    }
    
    userRepository.save(newUser);
    
    output.success = true;
    output.userId = newId;
    output.message = "User created successfully.";
    return output;
  }
}

public class Main {
  public static void main(String[] args) {
    IUserRepository repo = new InMemoryUserRepository();
    CreateUserUseCase useCase = new CreateUserUseCase(repo);

    CreateUserInput input = new CreateUserInput();
    input.name = "Alice";
    input.email = "alice@example.com";

    CreateUserOutput output = useCase.execute(input);

    if (output.success) {
      System.out.println("Result: " + output.message + " ID: " + output.userId);
    } else {
      System.out.println("Error: " + output.message);
    }

    // Test with invalid input
    CreateUserInput invalidInput = new CreateUserInput();
    invalidInput.name = "";
    invalidInput.email = "invalid";
    CreateUserOutput errorOutput = useCase.execute(invalidInput);
    System.out.println("Error test: " + errorOutput.message);
  }
}

Benefits of Use Cases

Using Use Cases brings significant advantages to your software design:

  • Isolation: Application-specific logic is isolated from UI, database, and frameworks.
  • Testability: Use Cases can be tested easily in isolation, without needing a UI or database connection.
  • Independence: Changes in the UI or database technology won't directly impact your core application logic.
  • Clarity: Each Use Case clearly defines a single feature or task of the application.

Use Case Interaction Flow

When a user interacts with your application, here's a simplified flow involving a Use Case:

  1. UI/Controller: Receives a request (e.g., button click).
  2. Input Port: The controller translates the request into a specific input format for the Use Case.
  3. Use Case: Executes its logic, orchestrating entities and interacting with repositories/gateways.
  4. Output Port: The Use Case provides its result in a generic output format.
  5. Presenter/UI: Transforms the Use Case output into something displayable to the user.

This flow ensures a clean separation of concerns.

Quick Check: Use Case's Role

Based on what you've learned, what is the primary role of a Use Case (Interactor) in Clean Architecture?

Recap: Orchestrating Actions

You've now learned about Use Cases, the application-specific orchestrators in Clean Architecture. They define your app's features, coordinate entities, and encapsulate business rules specific to the application.

By using Input and Output Ports, Use Cases remain independent of external layers, making your core logic highly testable, maintainable, and flexible to change. This is a crucial step towards building robust and adaptable software systems!

자주 묻는 질문

“사용 사례(인터랙터) 구현” 강의는 무료인가요?

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

“사용 사례(인터랙터) 구현”에서 뭘 배우나요?

엔터티를 조율해 애플리케이션의 특정 기능을 수행하고 애플리케이션에 특화된 비즈니스 규칙을 구현하는 사용 사례를 개발합니다. 브라우저에서 직접 실행하는 실습 코드로 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(으)로 돌아가기