Skip to content

Instantly share code, notes, and snippets.

@Hyodori04
Created March 5, 2023 10:27
Show Gist options
  • Save Hyodori04/9d48d2f7bc7de098c2cbae6001f90feb to your computer and use it in GitHub Desktop.
Save Hyodori04/9d48d2f7bc7de098c2cbae6001f90feb to your computer and use it in GitHub Desktop.
/* 절차
1. 추출하려는 표현식에 부작용은 없는지 확인한다.
2. 불변 변수를 하나 선언하고 이름을 붙일 표현식의 복제본을 대입한다.
3. 원본 표현식을 새로 만든 변수로 교체한다.
4. 테스트한다.
5. 표현식을 여러곳에서 사용한다면 각각을 새로 만든 변수로 교체한다. 하나 교체할 떄마다 테스트 한다.
*/
// 예시 1
// after
function price(order) {
// 가격 = 기본가격 - 수량 할인 + 배송비
return (
order.quantity * order.itemPrice -
Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 +
Math.min(order.quantity * order.itemPrice * 0.1, 100)
);
}
// before
// 변수 하나씩 순서대로 바꿔가면서 체크해야 한다(아래 코드는 전 과정을 거친 이후)
function pirce(order) {
const basePrice = order.quantity * order.itemPrice;
const quantityDiscount =
Math.max(0, order.quantity - 500) * order.itemPrice * 0.05;
const shipping = Math.min(basePrice * order.itemPrice * 0.1, 100);
return basePrice - quantityDiscount + shipping;
}
// 예시 2 (클래스 안에서)
// after
class Order {
constructor(aRecord) {
this._data = aRecord;
}
get quantity() {
return this._data.quantity;
}
get itemPrice() {
return this._data.itemPrice;
}
get price() {
return (
order.quantity * order.itemPrice -
Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 +
Math.min(order.quantity * order.itemPrice * 0.1, 100)
);
}
}
// before
class Order {
constructor(aRecord) {
this._data = aRecord;
}
get quantity() {
return this._data.quantity;
}
get itemPrice() {
return this._data.itemPrice;
}
get price() {
return basePrice - quantityDiscount + shipping;
}
get basePrice() {
return order.quantity * order.itemPrice;
}
get quantityDiscount() {
return Math.max(0, order.quantity - 500) * order.itemPrice * 0.05;
}
get shipping() {
return Math.min(basePrice * order.itemPrice * 0.1, 100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment