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 is ISP?

Welcome to the Interface Segregation Principle (ISP)! This principle is one of the five SOLID principles of object-oriented design.

At its core, ISP states that clients should not be forced to depend on interfaces they do not use. In simpler terms, don't make classes implement methods they don't need.

The Problem: Fat Interfaces

A 'fat interface' is an interface that contains too many methods, some of which are irrelevant to certain classes that implement it.

When a class implements a fat interface, it's forced to provide implementations for all methods, even those it doesn't use. This often leads to empty or placeholder method bodies, which is a code smell.

Fat Interface Example

Consider a general IWorker interface. While a human worker might perform all these actions, a robot worker might not eat or sleep. Let's see how this creates issues.

interface IWorker {
  void work();
  void eat();
  void sleep();
  void manageTeam();
}

class Robot implements IWorker {
  @Override
  public void work() {
    System.out.println("Robot working...");
  }
  @Override
  public void eat() {
    // Robots don't eat, forced to implement
    System.out.println("Robot can't eat.");
  }
  @Override
  public void sleep() {
    // Robots don't sleep, forced to implement
    System.out.println("Robot can't sleep.");
  }
  @Override
  public void manageTeam() {
    // Not all robots manage teams
    System.out.println("Robot can't manage team.");
  }
}

public class Main {
  public static void main(String[] args) {
    Robot robot = new Robot();
    robot.work();
    robot.eat(); // This call is meaningless for a robot
  }
}

Consequences of Fat Interfaces

As seen with the Robot example, implementing a fat interface leads to several problems:

  • Code Smells: Empty or placeholder method implementations.
  • Brittle Code: Changes to an interface (e.g., adding a new method) might force unrelated clients to update their code.
  • Reduced Cohesion: The interface has too many responsibilities, making it less focused.
  • Increased Coupling: Clients are coupled to methods they don't use, making the system harder to maintain and test.

Solution: Segregating Interfaces

The Interface Segregation Principle proposes splitting large, 'fat' interfaces into smaller, more specific ones.

Each client (class) then only implements the interfaces that are relevant to its specific responsibilities. This ensures clients are not forced to depend on methods they don't need.

ISP in Action: Refactored Code

Let's refactor our IWorker example by creating smaller, role-specific interfaces. Now, each worker type can implement only what it truly needs.

interface IWorkable {
  void work();
}

interface IEatable {
  void eat();
}

interface ISleepable {
  void sleep();
}

interface IManager extends IWorkable { // Managers also work
  void manageTeam();
}

class HumanWorker implements IManager, IEatable, ISleepable {
  @Override
  public void work() { System.out.println("Human working..."); }
  @Override
  public void eat() { System.out.println("Human eating..."); }
  @Override
  public void sleep() { System.out.println("Human sleeping..."); }
  @Override
  public void manageTeam() { System.out.println("Human managing team..."); }
}

class RobotWorker implements IWorkable { // Only works
  @Override
  public void work() { System.out.println("Robot working..."); }
}

public class Main {
  public static void main(String[] args) {
    HumanWorker human = new HumanWorker();
    human.work();
    RobotWorker robot = new RobotWorker();
    robot.work();
    // robot.eat(); // This would now be a compile error, as expected!
  }
}

Benefits of Using ISP

Applying ISP brings significant advantages to your software design:

  • Improved Cohesion: Interfaces become more focused and represent a single, clear responsibility.
  • Reduced Coupling: Clients depend only on the specific methods they require, leading to looser coupling.
  • Easier Maintenance: Changes to one interface don't impact clients that don't implement it.
  • Better Testability: Smaller, focused interfaces are easier to mock and test in isolation.
  • Flexibility: New functionalities can be added by creating new interfaces or extending existing small ones without affecting existing clients.

ISP in Practice

ISP is particularly useful in systems with diverse client types or complex functionalities:

  • Role-Based Systems: Different user roles (e.g., Administrator, Editor, Viewer) might interact with different parts of a system, each needing a specific interface.
  • API Design: When designing APIs, provide specific endpoints or interfaces for different client applications (e.g., mobile apps vs. web apps).
  • Plugin Architectures: Plugins can implement only the specific interfaces that define the functionalities they provide to the main application.

ISP vs. SRP: A Quick Look

While both ISP and the Single Responsibility Principle (SRP) promote focused design, they operate at different levels:

  • SRP (Single Responsibility Principle): Focuses on classes, stating a class should have only one reason to change.
  • ISP (Interface Segregation Principle): Focuses on interfaces and clients, ensuring clients aren't forced to depend on methods they don't use.

They often work hand-in-hand. Applying SRP to classes might naturally lead to clearer interfaces, and applying ISP can help classes better adhere to SRP by only implementing what's truly relevant to their single responsibility.

Check Your Understanding

Given an interface IDocumentProcessor with methods printDocument(), scanDocument(), faxDocument(), and copyDocument(), which of the following are good ways to apply the Interface Segregation Principle?

Lesson Summary

Great job! You've learned about the Interface Segregation Principle:

  • Clients should not be forced to depend on interfaces they do not use.
  • 'Fat interfaces' lead to irrelevant method implementations and brittle code.
  • ISP solves this by splitting large interfaces into smaller, client-specific ones.
  • This improves cohesion, reduces coupling, and makes code more maintainable and testable.

Keep these principles in mind to design more robust and flexible software!

자주 묻는 질문

“인터페이스 분리 원칙 실습” 강의는 무료인가요?

네 — “인터페이스 분리 원칙 실습” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 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(으)로 돌아가기