Open Closed Principle

Donghun Seol·2023년 4월 7일

개인적으로 OCP를 따르지 않아 코드가 장황해진 경험이 많다. 앞으론 숙지하고 적용해보자 😉

(...)개방, (...)폐쇄 원칙

확장에 대해서는 개방, 수정에 대해선 닫혀있어야 된다는 원칙이다.
코드에대한 원칙이 아니라 코드의 동작방식에 대한 원칙이다.

여러가지 동물들의 울음소리를 출력하는 코드를 예로 들어보자

OCP를 따르지 않는 코드

Cow와 같은 새로운 동물 종류가 추가될 때마다 cry함수도 변경해야 한다.
만약 100마리의 동물을 추가해야된다면 if-else문을 100번 추가해야한다.
좋지않다. 💩

class Animal {
  constructor(public type: string) {}
}

function cry(animal: Animal) {
  if (animal.type === 'Cat') { 
    console.log('meow');
  } else if (animal.type === 'Dog') {
    console.log('bowwow');
  } else {
    throw new Error('Not supported Animal type');
  }
}
const navi = new Animal('Cat');
const badukee = new Animal('Dog');

cry(navi);
cry(badukee);

// what if i have to add cow and what if i have to add hundreds of new animal types
const hwangSo = new Animal('Cow');
cry(hwangSo); // Error! 💩

OCP를 따르는 코드

인터페이스나 상위 클래스같은 계층을 삽입함으로써 구체적인 구현에 대한 정보 없이도
올바르게 호출 할 수 있으므로 OCP_Cry 메서드는 변경에는 닫혀있고 확장에는 열려 있는 OCP 원칙을 충실히 따르게 된다. 100마리의 다른 동물을 추가하더라도 OCP_cry함수는 변경하지 않아도 제대로 동작하게된다.

interface IAnimal {
  type: string;
  voice: string;
}

class OCP_Cat implements IAnimal {
  type = 'Cat';
  voice = 'meow';
}

class OCP_Dog implements IAnimal {
  type = 'Dog';
  voice = 'bowwow'
}

class OCP_Cow implements IAnimal {
  type = 'Cow';
  voice = 'm8o'
}
function OCP_Cry(animal: IAnimal) {
  console.log(animal.voice);
}

OCP_Cry(new OCP_Cat());
OCP_Cry(new OCP_Dog());
OCP_Cry(new OCP_Cow());

레퍼런스

위의 코드는 아래 강의에서 소개된 코드를 타입스크립트로 리팩터링한 코드입니다.
https://www.youtube.com/watch?v=EmnIdUvTRfk&t=4s

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

0개의 댓글