[TypeScript] OOP

수민🐣·2022년 12월 6일
0

TypeScript

목록 보기
13/16

Imperative and Procedural Programming 절차지향 프로그래밍

일이 진행되는 순서대로 프로그래밍하는 방법

  1. 하나를 수정하기 위해서 모든 코드를 이해해야함
  2. 사이드 이펙트 발생 위험
  3. 유지보수 x 확장성 x
{
  type CoffeeCup = {
    shots: number;
    hasMilk: boolean;
  };

  const BEANS_GRAMM_PER_SHOT: number = 7;

  let coffeeBeans: number = 0;
  function makeCoffee(shots: number): CoffeeCup {
    if (coffeeBeans < shots * BEANS_GRAMM_PER_SHOT) {
      throw new Error('Not enough coffee beans!');
    }
    coffeeBeans -= shots * BEANS_GRAMM_PER_SHOT;
    return {
      shots,
      hasMilk: false,
    };
  }

  coffeeBeans += 3 * BEANS_GRAMM_PER_SHOT;
  const coffee = makeCoffee(2);
  console.log(coffee);
}

Object Oriented Programming 객체지향적 프로그래밍

프로그램을 객체로 정해서 객체들끼리 의사소통! = 객체의 집합으로 프로그램을 표현하려는 프로그래밍 패러다임
서로 관련있는 데이터와 함수들을 object로 정의해서 프로그래밍 하는 것

  1. object 단위
  2. 한 곳에서 문제가 생기면 관련있는 object만 수정
  3. 여러번 반복 관련된 object 재사용
  4. 새로운 기능이 필요하다면 새로운 object

생산성 높음, 빠름, 높은 퀄리티, 유지보수 가능

{
  type CoffeeCup = {
    shots: number;
    hasMilk: boolean;
  };

  class CoffeeMaker {
    static BEANS_GRAMM_PER_SHOT: number = 7; // class level
    coffeeBeans: number = 0; // instance (object) level

    constructor(coffeeBeans: number) {
      this.coffeeBeans = coffeeBeans;
    }

    static makeMachine(coffeeBeans: number): CoffeeMaker {
      return new CoffeeMaker(coffeeBeans);
    }

    makeCoffee(shots: number): CoffeeCup {
      if (this.coffeeBeans < shots * CoffeeMaker.BEANS_GRAMM_PER_SHOT) {
        throw new Error('Not enough coffee beans!');
      }
      this.coffeeBeans -= shots * CoffeeMaker.BEANS_GRAMM_PER_SHOT;
      return {
        shots,
        hasMilk: false,
      };
    }
  }

  const maker = new CoffeeMaker(32);
  console.log(maker);
  const maker2 = new CoffeeMaker(14);
  console.log(maker2);

  const maker3 = CoffeeMaker.makeMachine(3);
}

0개의 댓글