Try   HackMD

Replace Derived Variable with Query

練習用的 REPL

class ProductionPlan { get production() { return this._production; } applyAdjustment(anAdjustment) { this._adjustments.push(anAdjustment); // this._production 在這邊做加總,但其實可以從 this._adjustments 內容算出來 this._production += anAdjustment.amount; } }

為了保險起見,先不改既有程式,而是先做 assert

class ProductionPlan { get production() { assert(this._production === this.calculatedProduction); return this._production; } // 這個 function 計算出來的結果,應該會跟 this._production 一樣 get calculatedProduction() { return this._adjustments.reduce((sum, a) => sum + a.amount, 0); } applyAdjustment(anAdjustment) { this._adjustments.push(anAdjustment); this._production += anAdjustment.amount; } }

確認 OK 後,可以移除 assert。

class ProductionPlan { get production() { return this._adjustments.reduce((sum, a) => sum + a.amount, 0); // OK 後才移除 assert } applyAdjustment(anAdjustment) { this._adjustments.push(anAdjustment); } }