🎁 < (단일 책임 원칙(Single Responsibility Principle) >🎁

 

단일 책임 원칙(Single Responsibility Principle)은 SRP이라고도 불린다. SRP는 Object-Oriented-Programming에서

매우 중요한 원칙 중 하나 이다.  이름에서 알 수 있듯이, 각각의 클래스는 단 한 가지의 책임만을 가져야 한다는 원칙이다.

이 원칙은 가독성과 유지보수성을 높이는데 있어 중요한 역할을 한다. 더 자세히 알아보자.

 

🤔  < (그래서.. 단일 책임 원칙이 뭘까?) >🤔 

SRP는 한 클래스는 하나의 책임만 가져야 한다는 개념. 즉, 클래스는 한 가지의 기능만을 수행해야 하며, 그 이상의 기능이 추가되면 별도의 클래스로 분리해야 된다는 것. 이를 통해 클래스의 복잡성을 줄일 수 있으며, 클래스가 자신의 책임을 더 잘 이해하고, 다른 클래스와 독립적으로 유지보수 및 수정이 가능해지는 것이다.

🐻‍❄️ < SRP의 필요성 >🐻‍❄️

이 원칙이 필요한 이유는 간단하다. 한 클래스가 여러 가지 책임을 가질 경우, 클래스의 복잡성이 증가하고, 한 책임에 대한 변경이 다른 책임을 가진 코드에 영향을 미칠 가능성이 높아진다.

 

예를 들어, 계산기 클래스가 있을 때, 이 클래스가 숫자 계산뿐만 아니라 파일에서 데이터를 읽고,결과를 파일에 쓰는 역할까지 수행하게 된다면, 이 클래스는 두 가지의 책임을 가지게 된다. 이렇게 되면, 계산 로직과 파일 입출력ㅇ 로직이 서로 간섭할 수 있으며, 한 가지 로직의 수정이 다른 로직에도 영향을 끼칠 수 있다.

 

< SRP를 위반한 예시 >

public class Calculator {
  private List numbers = new ArrayList<>();
  private int result;
  
  public void loadNumbersFromFile(String fileName) {
     // 파일에서 숫자를 로드하여 numbers 리스트에 추가하는 코드
  }
  public void addNumber(int number){
    numbers.add(number);
  }
  public void calculateSum() {
    result = 0;
    for(int number : numbers) {
      result += number;
    }
  }
  
 public void saveResultToFile(String fileName){
 //결과를 파일에 저장하는 코드   
 }
}  
}

위 코드에서 Calculator 클래스는 숫자를 더하는 책임과 파일 입출력 책임을 동시에 가지고 있다.

< SRP를 준수한 예시 >

public class Calculator {
    private List numbers = new ArrayList<>();
    private int result;

    public void addNumber(int number) {
        numbers.add(number);
    }

    public void calculateSum() {
        result = 0;
        for (int number : numbers) {
            result += number;
        }
    }
}

위의 코드에서는 Calculator 클래스는 숫자를 더하는 책임만 가지고 있다. 파일 입출력은 별도의 클래스에서 담당하도록 분리되었다. 이렇게 하면 클래스의 책임이 명확하게 구분되며, 코드의 가독성과 유지보수성이 향상된다.

 

Reference: Wikipedia: Single Responsibility Principle

 

Single-responsibility principle - Wikipedia

From Wikipedia, the free encyclopedia Computer programming principle The single-responsibility principle (SRP) is a computer programming principle that states that "A module should be responsible to one, and only one, actor."[1] The term actor refers to a

en.wikipedia.org

StackOverflow: What is the Single Responsibility Principle?

 

 

Get a Count from a MYSQL Inquire

I'm pretty novice at MYSQL, but I'm attempting to get a count from a MYSQL select I already have. Pretty much, I'd like to count the number of items, then group them by what their locations.locatio...

stackoverflow.com

 

+ Recent posts