練習用的 REPL
class Order {
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
var basePrice = this._quantity * this._item.price; // Temp Variable
var discountFactor = 0.98; // Temp Variable
if (basePrice > 1000) discountFactor -= 0.03;
return basePrice * discountFactor;
}
}
class Order {
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
const basePrice = this._quantity * this._item.price; // Make it read-only
var discountFactor = 0.98;
if (basePrice > 1000) discountFactor -= 0.03;
return basePrice * discountFactor;
}
}
把計算 basePrice 的方法抽出來。
class Order {
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
const basePrice = this.basePrice;
var discountFactor = 0.98;
if (basePrice > 1000) discountFactor -= 0.03;
return basePrice * discountFactor;
}
get basePrice() { // Extract logic, make sure no side-effect
return this._quantity * this._item.price;
}
}
class Order {
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
var discountFactor = 0.98;
if (this.basePrice > 1000) discountFactor -= 0.03; // Replace temp variable with query
return this.basePrice * discountFactor; // Replace temp variable with query
}
get basePrice() {
return this._quantity * this._item.price;
}
}
把計算 discountFactor 的方法也抽出來。
class Order {
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
const discountFactor = 0.98; // Make it read-only
if (this.basePrice > 1000) discountFactor -= 0.03;
return this.basePrice * discountFactor;
}
get basePrice() {
return this._quantity * this._item.price;
}
get discountFactor() { // Extract logic, also make sure no side-effect
var discountFactor = 0.98;
if (this.basePrice > 1000) discountFactor -= 0.03;
return discountFactor;
}
}
這是最終結果。
class Order {
constructor(quantity, item) {
this._quantity = quantity;
this._item = item;
}
get price() {
return this.basePrice * this.discountFactor; // Result!
}
get basePrice() {
return this._quantity * this._item.price;
}
get discountFactor() {
var discountFactor = 0.98;
if (this.basePrice > 1000) {
discountFactor -= 0.03;
}
return discountFactor;
}
}