IT책, 강의/리팩터링
12 - 상속 다루기 - 생성자 본문 올리기
제로칼로리
2023. 10. 27. 13:19
개요
생성자는 특수한 메서드이기 때문에 리팩터링도 다른 식으로 접근해야 한다.
리팩터링이 간단히 끝날 것 같지 않다면 생성자를 팩터리 함수로 바꾸기를 고려한다.
예시
class Party{} class Employee extends Party{ constructor(name, id, monthlyCost){ super(); this._id = id; this._name = name; this._monthlyCost = monthlyCost; } } class Department extends Party{ constructor(name, staff){ super(); this._name; this._staff = staff; } } |
class Party{ constructor(name){ this._name = name; } } class Employee extends Party{ constructor(name, id, monthlyCost){ super(name); this._id = id; this._monthlyCost = monthlyCost; } } class Department extends Party{ constructor(name, staff){ super(name); this._staff = staff; } } |
예시 : 공통 코드가 나중에 올 때
class Employee{ constructor(name){ } get isPrivileged(){} assignCar(){} } //예시 : 공통 코드가 나중에 올때 class Manager extends Employee{ constructor(name, grade){ super(name); this._grade = grade; if(this.isPrivileged) this.assignCar();//모든 서브클래스가 수행함 } get isPrivileged(){ return this._grade >4; } } |
class Manager extends Employee{ constructor(name, grade){ super(name); this._grade = grade; this.finishConstruction(); } //먼저 공통 코드를 함수로 추출 finishConstruction() { if (this.isPrivileged) this.assignCar(); } get isPrivileged(){ return this._grade >4; } } |
class Employee{ constructor(name){ } get isPrivileged(){} assignCar(){} //슈퍼클래스로 옮김 finishConstruction() { if (this.isPrivileged) this.assignCar(); } } class Manager extends Employee{ constructor(name, grade){ super(name); this._grade = grade; this.finishConstruction(); } get isPrivileged(){ return this._grade >4; } } |