기록/TIL(Today I Learned)
[TypeScript]캡슐화??
solutionMan
2022. 11. 2. 14:03
반응형
절차지향 프로그래밍
{
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: shots,
hasMilk: false,
};
}
coffeeBeans = 3 * BEANS_GRAMM_PER_SHOT
const coffee = makeCoffee(2);
console.log(coffee);
}
Class를 적용하여 객체 지향형으로 변경
coffeeMaker라는 내용에 필요한 것(데이터 + 함수)들만 추가 하여 클래스 생성
{
type CoffeeCup = {
shots: number;
hasMilk: boolean;
};
class CoffeMaker {
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): CoffeMaker {
return new CoffeMaker(coffeeBeans);
}
makeCoffee(shots: number): CoffeeCup {
if (this.coffeeBeans < shots * CoffeMaker.BEANS_GRAMM_PER_SHOT) {
throw new Error("Not enough coffee beans!");
}
this.coffeeBeans -= shots * CoffeMaker.BEANS_GRAMM_PER_SHOT;
return {
shots: shots,
hasMilk: false,
};
}
}
const maker = new CoffeMaker(32);
console.log(maker);
console.log(maker.makeCoffee(2));
console.log(CoffeMaker.makeMachine(3));
}
캡슐화
캡슐화를 해야하는 이유
const maker = new CoffeMaker(32);
maker.coffeeBeans =3;
maker.coffeeBeans = -32;//invalid
위와 같이 외부에서 CoffeMaker Class의 인자를 수정하는것은 옳지 않다.
우리의 의도와는 전혀 맞지가 않다.
이러한 직접적인 수정을 막기위해서 private를 이용하여 외부에서 바로 위 인자들을 다룰수없게 하여 캡슐화(은닉) 해준다.
private static BEANS_GRAMM_PER_SHOT: number = 7; //class level
private coffeeBeans: number = 0; //instance (object) level
위와 같인 직접적인 수정을 막은 대신 함수를 이용(fillCoffeeBeans)하여 내부의 상태를 변경할 수 있도록 한다.
fillCoffeeBeans(beans: number) {
if (beans < 0) {
throw new Error("커피콩을 갯수는 0보다 커야한다.");
}
this.coffeeBeans += beans;
}
이렇게 함수를 만들어서 인자를 다룰 경우 올바른지 않은지 또한 한번 더 에러 처리를 해놓음으로써 좀더 안정성있게 만들수가 있다.
반응형