Single Responsibility Principle

Donghun Seol·2023년 4월 7일
0

단일 책임 원칙

클래스를 변경하는 이유는 단 한 가지여야 한다. (로버트 C. 마틴)

클래스를 변경하는 이유가 한 가지이기 위해서는 하나의 액터에 대한 책임만 가지고 있어야 한다.
책임은 하나의 특정 액터를 위한 기능 집합이고, 액터란 기능(=클래스 ,모듈)을 사용하는 주체입니다.
따라서 SRP에 맞는 클래스나 함수는 하나의 논리적 단위만 담당해야 한다.

아래의 코드에서 WrongCat은 Cat과 관계없는 print()라는 메서드를 포함하여 SRP를 위반하였다.
이를 SRP에 맞게 수정하면 RightCat처럼 변경할 수 있다. 고양이가 자신을 프린트하는 기능을 갖고 있는건 어색하다.

class WrongCat {
  constructor(public name: string, public age: number) {}
  run() {
    console.log('cat running');
  }
  walk() {
    console.log('cat walking');
  }
  cry() {
    console.log('cat meow');
  }
  print() {
    console.log(`name: ${this.name}, age: ${this.age}`);
  }
}

class RightCat {
  constructor(public name: string, public age: number) {}
  run() {
    console.log('cat running');
  }
  walk() {
    console.log('cat walking');
  }
  cry() {
    console.log('cat meow');
  }
  represent() {
    return `name:${this.name}, age:${this.age}`;
  }
}

const wCat = new WrongCat('navi', 11);
wCat.print();

const gCat = new RightCat('nero', 3);
console.log(gCat.represent());

레퍼런스

https://www.youtube.com/watch?v=Tit-bJJm9iw
https://yoongrammer.tistory.com/96

profile
I'm going from failure to failure without losing enthusiasm

0개의 댓글