死程序不说谎 在webpack部分最后,我们用断言assert代替之前的throw Error。 首先,我们在之前的代码ActionData里面:
export default class ActionData {
//
constructor(type, lineWidth, strokeStyle) {
this._type = type;
this._lineWidth = lineWidth;
this._strokeStyle = strokeStyle;
}
//
draw(ctx) { throw new Error('draw not implemented'); }
}
复制代码
draw方法实现里面,我们直接抛出了一个异常。这表明,如果不应该运行到这里。因为这个方法,是需要子类去实现的。如果子类没有实现,就会出现这个异常。 在这种情况下,对于出现了我们认为不应该出现的情况,我们应该尽快让程序停止运行,而不应该忽略这种错误,让程序错误的运行下去。否则的话,我们可能会很久都无法发现这个错误,也有可能会导致错误要花很长事件才能找到原因。 在之前,我们直接抛出异常。现在我们可以换用更好的方式:assert。
import assert from 'assert';
export default class ActionData {
//
constructor(type, lineWidth, strokeStyle) {
this._type = type;
this._lineWidth = lineWidth;
this._strokeStyle = strokeStyle;
}
//
draw(ctx) { assert(false, 'draw not implemented'); }
}
复制代码
从下次开始,我们将开始使用react来改造我们的程序,让我们的程序更加漂亮。