7-4. 임시 변수를 질의 함수로 바꾸기

적용 시점

  • 참조할 목적으로 만든 변수를 아예 함수로 만든다.

  • 변수에 값을 한 번 대입한 뒤 더 복잡한 코드 덩어리에서 여러 차례 다시 대입이 이루어지는 경우

절차

  1. 변수가 사용되기 전에 값이 확실히 결정되는지, 변수를 사용할 때마다 계산 로직이 매번 다른 결과를 내지는 않는지 확인한다.

  2. 읽기전용으로 만들 수 있는 변수는 읽기전용으로 만든다.

  3. 테스트한다.

  4. 변수 대입문을 함수로 추출한다.

  5. 테스트한다.

  6. 변수 인라인하기로 임시 변수를 제거한다.

예시

❌Before

const ProductInfo {
	constructor({ product, discountPercent, price, quantity }) {
		this._product = product;
		this._discountPercent = discountPercent,
		this._price = price;
		this._quantity = quantity;
	}
	get discountPrice() {
		const basePrice = this._price * this._quantity;
		return basePrice * this._discountPercent,
	}
}

⭕After

const ProductInfo {
	constructor({ product, discountPercent, price, quantity }) {
		this._product = product;
		this._discountPercent = discountPercent,
		this._price = price;
		this._quantity = quantity;
	}
	get basePrice () {
		return this._price * this._quantity;
	}
	get discountPrice() {
		return basePrice * this._discountPercent,
	}
}

Last updated