Saturday, April 4, 2015

Moving the date range code into an Angular directive

At the end of last post, we had eliminated some duplication from an Angular controller by using events to make it communicate with some of the widgets it was using. This was the code at that moment:

Next we got advantage of the decoupling given by using events to move the rest of the code that had to do with the date range widget to an Angular directive.

First we created the directive:

where we moved the code that creates and initializes the date range widget.

Then we moved all the html that was using the date range widget in track-index.html to the date-range.html template:

In track-index all this code got substituted by:

This is how the controller's code looks now:

Notice how the dateRangeWidgetFactory is not being injected into the controller any more and the widget creation and initilization code is gone.

We should have probably used a similar design from the very beginning (with a directive, a widget and communicating through events) but we didn't, because we were in a hurry, still learning how the page design was meant to be and still learning a way to avoid repeating past errors in Angular applications.

Compare the current version of the code with how it looked at the beginning (it was much longer, I'm only showing the date range related code):

The date range logic in this initial version had no tests at all and in fact it had some bugs...

Then we started working on it by extracting its code to a plain JavaScript object and testing it (as we described for a different case here), eliminating some remaining duplication in the controller making it work with events (described in here) and finally created an Angular directive for it.

I think we did something similar to what Liz Keogh writes in her post If you can’t write tests first, at least write tests second:
  • We didn't know how to test first this code and we were under a situation of flux, high uncertainty and time pressure, so we wrote a messy code that mostly worked. Then from there, we put it under a test harness and started improving its design.

No comments:

Post a Comment