"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 단일 책임 원칙

단일 책임 원칙

2024-11-09에 게시됨
검색:425

Single Responsibility Principle

모든 소프트웨어 구성 요소에는 하나의 책임만 있어야 합니다.

소프트웨어 구성요소는 클래스, 메소드 또는 모듈일 수 있습니다.

예, 스위스 군용 칼은 소프트웨어 개발의 단일 책임 원칙을 위반하는 다목적 도구입니다. 대신 칼은 단일 책임을 따르는 좋은 예입니다(스위스 군용 칼과 달리 절단에만 사용할 수 있으므로) 자르거나 캔을 여는 데 사용할 수 있으며 마스터 키, 가위 등으로 사용할 수 있습니다.)

현실 세계에서든 소프트웨어 개발에서든 변화는 끊임없이 일어나기 때문에 단일 책임 원칙의 정의도 이에 따라 변합니다.

모든 소프트웨어 구성요소에는 변경해야 할 단 하나의 이유가 있어야 합니다.


아래 Employee 클래스에서 변경이 발생할 수 있는 이유는 세 가지입니다.

  1. 직원 속성 변경
  2. 데이터베이스 변경
  3. 세금 계산 변경
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * Employee class has details of employee
 * This class is responsible for saving employee details, getting tax of
 * employee and getting
 * details of employee like name, id, address, contact, etc.
 */
public class Employee {
    private String employeeId;
    private String employeeName;
    private String employeeAddress;
    private String contactNumber;
    private String employeeType;

    public void save() {
        String insert = MyUtil.serializeIntoString(this);
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password");
            statement = connection.createStatement();
            statement.execute("insert into employee values ("   insert   ")");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void calculateTax() {
        if (this.getEmployeeType().equals("fulltime")) {
            // tax calculation for full time employee
        } else if (this.getEmployeeType().equals("contract")) {
            // tax calculation for contract type employee
        }
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getEmployeeType() {
        return employeeType;
    }

    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

}

SRP(단일 책임 원칙)에서는 클래스에서 변경 이유를 하나만 권장하므로 Employee 클래스를 일부 수정해야 합니다.


SRP에 의한 변경 사항

이제 Employee 클래스에서 변경이 발생할 수 있는 이유는 단 하나입니다.

변경 이유: 직원 속성 변경

/**
 * Employee class has details of employee
 */
public class Employee {
    private String employeeId;
    private String employeeName;
    private String employeeAddress;
    private String contactNumber;
    private String employeeType;

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

    public void calculateTax() {
       new TaxCalculator().calculateTax(this);
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getEmployeeType() {
        return employeeType;
    }

    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

}

또한 EmployeeRepository 클래스에서 변경이 발생할 수 있는 이유는 단 하나입니다.

변경 이유: 데이터베이스 변경

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class EmployeeRepository {

    public void save(Employee employee) {
         String insert = MyUtil.serializeIntoString(employee);
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password");
            statement = connection.createStatement();
            statement.execute("insert into employee values ("   insert   ")");

        } catch (Exception e) {
            e.printStackTrace();
        }
}

}

마지막으로 TaxCalculator 클래스에서 변경이 발생할 수 있는 이유는 단 하나입니다.

변경 사유: 세금 계산 변경

public class TaxCalculator {

    public void calculateTax(Employee employee) {
        if (employee.getEmployeeType().equals("fulltime")) {
            // tax calculation for full time employee
        } else if (employee.getEmployeeType().equals("contract")) {
            // tax calculation for contract type employee
        }
    }
}

참고: 이제 3개 클래스 모두 단일 책임 원칙을 따르므로 두 정의를 모두 따릅니다.

클래스나 소프트웨어 구성 요소를 만들 때 다음 사항을 염두에 두세요. 높은 응집력과 느슨한 결합을 목표로 하세요.

모든 소프트웨어 구성 요소에는 하나의 책임만 있어야 합니다.
모든 소프트웨어 구성요소에는 변경해야 할 단 하나의 이유가 있어야 합니다.

릴리스 선언문 이 기사는 https://dev.to/prashantrmishra/single-responsibility-principle-m8n?1에서 복제됩니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3