단일 책임 원칙(Single Responsibility Principle, SRP)

2023. 10. 29. 20:10· SOLID 원칙
목차
  1. 단일 책임 원칙(Single Responsibility Principle, SRP)
  2. 정의
  3. 적용
  4. 왜 소프트웨어 컴포넌트를 변경할 이유는 오직 하나여야 하는가?

 

단일 책임 원칙(Single Responsibility Principle, SRP)

 


 

정의

  • 소프트웨어에서 하나의 컴포넌트는 단 하나의 책임을 가져야 한다.
  • 소프트웨어 컴포넌트를 변경할 이유는 오직 하나여야 한다.
  • 맥가이버 칼 같은 클래스를 만들지 말고, 단일 나이프를 만들어라.

 

 


 

적용

 

1. 각각의 컴포넌트는 응집력(Cohesion) 을 높이는 방향으로 설계해야 한다.

// Bad Example
public class Square {

    int side = 5;

    public int getArea() {
        return side * side;
    }

    public int getPerimeter() {
        return 4 * side;
    }

    public void draw() {
        // draw the square image
    }

    public void rotate(int degree) {
        // rotate the square to clockwise
        // rerender the square image
    }
}
  • 위의 코드는 Square 클래스가 응집력이 높지 않다.
  • getArea()와 getPerimeter()는 Square의 정보를 반환하는 메서드이다.
  • draw()와 rotate()는 Square를 그리는 메서드이다.

 

// Good Example
public class Square {

    int side = 5;

    public int getArea() {
        return side * side;
    }

    public int getPerimeter() {
        return 4 * side;
    }
}

public class SquareDrawer {

    public void draw(Square square) {
        // draw the square image
    }

    public void rotate(Square square, int degree) {
        // rotate the square to clockwise
        // rerender the square image
    }
}
  • 위의 코드는 Square 클래스와 SquareDrawer 클래스로 분리하여 응집력을 높였다.
  • Square 클래스는 Square의 정보를 반환하는 메서드만을 가지고 있다.
  • SquareDrawer 클래스는 Square를 그리는 메서드만을 가지고 있다.

 

2. 컴포넌트 간의 결합력(Coupling) 을 낮춰야 한다.

// Bad Example
public class Student {

    private String studentId;
    private String studentName;
    private Date studentBirth;

    public void save() {
        // Serialize object into a string representation
        String objectStr = MyUtils.serialize(this);
        Connection connection = null;
        Statement statement = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
            statement = connection.createStatement();
            statement.execute("INSERT INTO student VALUES (" + objectStr + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    ...
}
  • save() 메서드는 Student 객체를 직렬화하여 DB에 저장하는 메서드이다.
  • 현재의 코드는 Student 클래스가 DB에 종속되어 결합력(Coupling)이 높다.
  • 만약 DB가 MySQL이 아닌 다른 DB로 변경된다면 Student 클래스의 코드를 수정해야 한다.

 

// Good Example
public class Student {

    private String studentId;
    private String studentName;
    private Date studentBirth;

    public void save() {
        new StudentRepository().save(this);
    }

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    ...
}

public class StudentRepository {

    public void save(Student student) {
        // Serialize object into a string representation
        String objectStr = MyUtils.serialize(student);
        Connection connection = null;
        Statement statement = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
            statement = connection.createStatement();
            statement.execute("INSERT INTO student VALUES (" + objectStr + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 위의 코드는 Student 클래스와 StudentRepository 클래스로 분리하여 결합력을 낮췄다.
  • Student 클래스는 학생과 관련된 정보를 가지고 있다.
  • StudentRepository 클래스는 Student 객체를 DB에 저장하는 메서드만을 가지고 있다.

 

 


 

왜 소프트웨어 컴포넌트를 변경할 이유는 오직 하나여야 하는가?

  • 소프트웨어 컴포넌트를 변경할 이유가 여러 개라면, 그 만큼 해당 컴포넌트를 변경하는 경우도 많아진다.
  • 변경 은 버그를 발생시키는 가장 큰 원인이다.
  • 때문에 소프트웨어 컴포넌트를 변경할 이유는 오직 하나로 두고, 변경을 최소화해야 한다.

 

  1. 단일 책임 원칙(Single Responsibility Principle, SRP)
  2. 정의
  3. 적용
  4. 왜 소프트웨어 컴포넌트를 변경할 이유는 오직 하나여야 하는가?
'SOLID 원칙' 카테고리의 다른 글
  • 인터페이스 분리 원칙(Interface Segregation Principle, ISP)
  • 리스코프 치환 원칙의 다른 예시들
  • 리스코프 치환 원칙(Liskov Substitution Principle, LSP)
  • 개방 폐쇄 원칙(Open-Close Principle, OCP)
gerrymandering
gerrymandering
gerrymandering
gerrymandering
gerrymandering
전체
오늘
어제
  • 분류 전체보기 (78)
    • SOLID 원칙 (6)
    • 번역 (4)
    • Nginx (1)
    • Tailwind CSS (1)
    • AWS (7)
      • DMS를 사용한 RDS to OpenSearch .. (3)
      • ECS를 이용한 Blue-Green 무중단 배포 .. (7)
    • NextJS (4)
    • 기타 (10)
    • Prompt Engineering (6)
    • 읽어볼만한 글 (3)
      • 기술 (0)
      • 쓸만한 툴 (0)
      • 아이템 (0)
      • 웹 디자인 (0)
      • 기타 (3)
    • Cloud Architecture (4)
    • Trouble Shooting (9)
    • Spring (11)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

최근 댓글

최근 글

글쓰기 / 관리자
hELLO · Designed By 정상우.v4.2.1
gerrymandering
단일 책임 원칙(Single Responsibility Principle, SRP)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.