HTML and CSS Reference
In-Depth Information
Running the test reveals that the current implementation blows up along with
the first observer, causing the second observer not to be called. In effect, noti-
fyObservers is breaking its guarantee that it will always call all observers once
they have been successfully added. To rectify the situation, the method needs to be
prepared for the worst, as seen in Listing 11.29.
Listing 11.29 Catching exceptions for misbehaving observers
function notifyObservers() {
for (var i = 0, l = this.observers.length; i < l; i++) {
try {
this.observers[i].apply(this, arguments);
} catch (e) {}
The exception is silently discarded. It is the observers responsibility to ensure
that any errors are handled properly, the observable is simply fending off badly
behaving observers.
11.5.3 Documenting Call Order
We have improved the robustness of the Observable module by giving it proper
error handling. The module is now able to give guarantees of operation as long as it
gets good input and it is able to recover should an observer fail to meet its require-
ments. However, the last test we added makes an assumption on undocumented
features of the observable: It assumes that observers are called in the order they
were added. Currently, this solution works because we used an array to implement
the observers list. Should we decide to change this, however, our tests may break.
So we need to decide: Do we refactor the test to not assume call order, or do we
simply add a test that expects call order, thereby documenting call order as a fea-
ture? Call order seems like a sensible feature, so Listing 11.30 adds the test to make
sure Observable keeps this behavior.
Listing 11.30 Documenting call order as a feature
"test should call observers in the order they were added":
function () {
var observable = new tddjs.util.Observable();
var calls = [];
var observer1 = function () { calls.push(observer1); };
var observer2 = function () { calls.push(observer2); };
Search WWH ::

Custom Search