HTML and CSS Reference
In-Depth Information
By throwing an exception already when adding the observers we don't need
to worry about invalid data later when we notify observers. Had we been pro-
gramming by contract, we could say that a precondition for the addObserver
method is that the input must be callable. The postcondition is that the observer
is added to the observable and is guaranteed to be called once the observable calls
notifyObservers .
The test fails, so we shift our focus to getting the bar green again as quickly
as possible. Unfortunately, there is no way to fake the implementation this time—
throwing an exception on any call to addObserver will fail all the other tests.
Luckily, the implementation is fairly trivial, as seen in Listing 11.27.
Listing 11.27 Throwing an exception when adding non-callable observers
function addObserver(observer) {
if (typeof observer != "function") {
throw new TypeError("observer is not function");
addObserver now checks that the observer is in fact a function before adding
it to the list. Running the tests yields that sweet feeling of success: All green.
11.5.2 Misbehaving Observers
The observable now guarantees that any observer added through addObserver
is callable. Still, notifyObservers may still fail horribly if an observer throws
an exception. Listing 11.28 shows a test that expects all the observers to be called
even if one of them throws an exception.
Listing 11.28 Expecting notifyObservers to survive misbehaving observers
"test should notify all even when some fail": function () {
var observable = new tddjs.util.Observable();
var observer1 = function () { throw new Error("Oops"); };
var observer2 = function () { observer2.called = true; };
Search WWH ::

Custom Search