Tuesday, October 4, 2016

On Learning (Compendious Thunks)


Cross-posted on: Compendious Thunks

My name is Chris. I am an Obsessive Pragmatic Programmer learner.

OK, that might sound completely made up (it is), but bear with me...

What makes one a pragmatically obsessive learner? Well two things:

Is that the absolute best way to learn?


Beats me.

No, really. If I've learned anything while exploring learning, it is that each of us has to find what works best for us. And we can't shirk the responsibility of learning in the programming field. It will pass you by if you let up for a week.

What I can say about Obsessive Pragmatic Learning is that it's pretty darn effective for me. How could you not pick up a thing or two after 1900 blog posts? And, yup, I'd highly recommend giving it a try -- even to the point of daily blogging. *

But...


Lately, I begin to feel like certain fundamentals are slipping. I'm pretty sure that The Pragmatic Programmer never meant for anyone to learn new stuff to the exclusion of all other learning. That's on me.

So... I commit now to taking a step back. Instead of learning another new library, a new language, or the next hot framework, I will instead invest in fundamentals. I will start with design patterns, then move onto software principles. Eventually I will move back to the next hot framework because I really do think there is a balance to be found.

And I hope you will join me at...

Compendious Thunks!


Effective learning doesn't have to be obsessive (and, let's face it, it probably shouldn't be). It should be committed. Toward that goal, I think we can help each other.

So I present to you Compendious Thunks. And a bargain:

For you: You watch 5 minute screencasts to level up. Roughly twice a week, watch an episode on a pattern or principle, play with interactive code, and... get better! You continue your growth from good to greatness.

For me: I keep learning and recommit myself to my fundamentals. And get feedback from you where I still need to get better or improve my understanding.

I'm making much of this free as I hope it'll prove useful. And the rest I'm making as informative as humanly possible.

Let's redouble a focus on programming fundamentals together!



* Well, blog daily as long as you don't wind up doing it for 1,045 days straight. I'd very much like to hold onto that little record, thank you very much!


Sunday, February 21, 2016

A Facade for the Chain of Responsibility


How much should the client know about the implementation of the chain of responsibility pattern? I have reworked my spreadsheet cell formatting example to the point that I am quite satisfied with the code organization and how it responds:



What leaves me slightly less satisfied is how much the Dart constructing code needs to know about the underlying implementation. Currently, I have it constructing the individual links in the chain and assigning those links:
  var textFormat = new TextFormatter();
  var dateFormat = new DateFormatter(textFormat);
  var numberFormat = new NumberFormatter(dateFormat);
I do not think it too horrible that the constructing code needs to know about the individual formatters—especially since it needs to know how to remove some of them in response to checkbox changes. What bugs me here is the same thing that has bugged me about other examples that I have built—the requirement that the constructing code know which link is first, which link has to be constructed first, and with which links each can and should link.

That is, the text-formatter is the default link, so it needs to be last in the chain, but it has to be constructed first so that the second-to-last link can point to it. It is also not a good idea to remove the text-formatter (even though I have a checkbox in the UI) because it is the default cell formatter. Lastly, I find it awkward to tell the on-change listener to number-format cells when establishing the request handler:
  container.onChange.listen(numberFormat);
Even though it looks like I am asking for number formatting, I am really asking for something in the cell formatting chain to handle the request—number format just happens to be the first.

In some (most?) implementations of the chain of responsibility this might actually be OK or desired organization. In this case, I think a facade wants to be in front of this complexity. So I define CellFormatter such that it declares the individual link components:
class CellFormatter {
  var _numberFormat = new NumberFormatter();
  var _dateFormat = new DateFormatter();
  var _textFormat = new TextFormatter();

  var first;
  // ...
}
I also declare a pointer to the first cell-formatting object so that I know where to start requests and can easily update it. In the constructor, I then establish the links in the chain and initially set first:
class CellFormatter {
  // ...
  CellFormatter() {
    _numberFormat.nextHandler = _dateFormat;
    _dateFormat.nextHandler = _textFormat;
    first = _numberFormat;
  }
  // ...
}
The call() method is then simple enough—I send the event request onto the call() method of the first link in the chain:
class CellFormatter {
  // ...
  void call(Event e) { first.call(e); }
  // ...
}
And, as mentioned, it is easy to manipulate the chain with methods like ignore() and obey(). A simple implementation for the number formatter could be:
class CellFormatter {
  // ...
  void ignore(String format) {
    if (format == 'number') first = _dateFormat;
    // ...
  }
  void obey(String format) {
    if (format == 'number') first = _numberFormat;
    // ...
  }
}
I feel more comfortable putting this knowledge in a class than I would in the main code. At least for this example, this seems like too much maintenance to mingle with other code.

This does lead to some significant improvements in the main code. Obviously, it is much simpler to instantiate one object instead of three (and to omit the linking):
  var cellFormat = new CellFormatter();
I also get the benefit of an easier to read (and hence easier to maintain) assignment of the cell-formatter:
  container.onChange.listen(cellFormat);
This one-liner reads nicely and has low cognitive requirements: when the spreadsheet container sees changes, it cell-formats the source elements. No worry about the chain or the first element in the chain. Formatting is done by the cell formatter. Simple!

(see last night's post for why cellFormat behave like a function here)

The nicest win in this approach may be in the code that ignores/obeys formatters. Previously, when ignoring the number formatter, I had to obtain a subscription from the initial listener so that I could then cancel it and start a new listener with the second link in the chain:

  var subscription= container.onChange.listen(numberFormat);

  query('#no-numbers').onChange.listen((e){
    var el = e.target;
    if (el.checked) {
      subscription.cancel();
      subscription = c.stream.listen(dateFormat);
    }
    // ...
  });
Now that CellFormatter internally maintains a reference to the first item in the chain, I no longer need to worry about the stream subscription sending to the wrong first element. The resulting code is mercifully free from subscription code, only obeying or ignoring links as requested:

  container.onChange.listen(cellFormat);

  query('#no-numbers').onChange.listen((e){
    var el = e.target;
    if (el.checked) {
      cellFormat.ignore('number');
    }
    // ...
  });
That seems a nice improvement.

Overall, I am very happy with the improvement in the code as a results of this approach. I have yet to examine it in depth, but I believe this is likely a facade pattern as it hides some of the underlying complexity of the chain of responsibility from the calling context. Regardless of what it is called, I very much like it!

This seems a nice stopping point for my research into the chain of responsibility. Up next, who knows?

Play with the code on DartPad: https://dartpad.dartlang.org/adf7e28a00eba10491e9.


Day #102

Saturday, February 20, 2016

Call the Chain of Responsibilty


Design patterns are pretty boring. Experimenting with design patterns? That's where the fun is!

While messing about with spreadsheet formatting objects (e.g. date, text, numeric), it occurred to me that there might be a Dartier (cooler) solution than what I am currently using:
abstract class CellFormatter {
  CellFormatter nextHandler;

  void processRequest(Event e) {
    if (handleRequest(e)) return;
    if (nextHandler == null) return;

    nextHandler.processRequest(e);
  }

  // Subclasses handle requests as needed
  bool _handleRequest(Event e) => false;
  // ...
}
In this handler, I am both implementing and connecting the successors. The nextHandler property points to the next object in the chain. The processRequest() method is responsible for sending requests to that next object when the current object opts against handling the request (e.g. when a number formatter sees text in a cell).

There is nothing wrong with this approach, but I have a nagging dislike for the naming convention that I have here. One method is called processRequest() and the other is _handleRequest(). "Process" and "handle" both have similar meanings so it takes a little extra noodling here to understand what is happening. Since processRequest() is public, that is a good indication that it is the public interface to the chain. Less obvious is that processRequest() is responsible for connecting to the successor whereas the _handleRequest() is meant solely for subclasses to actually handle the request.

The main problem here is the dual nature of processRequest(). To the outside world, it is… processing the request, so it is well-named in that respect. Actually looking at the code, however, it serves the different purpose of linking successors. And naming _handleRequest() as I have only adds to the confusion. This is not horrible, but I can do better.

Perhaps renaming processRequest() as just process() will help. To the outside world, it retains a similar connotation. Inside the code, it seems more distinct from _handleRequest(). Or maybe…

I can rename it as call().

The beautiful thing about a method named call() in Dart is that automatically makes the current class into a function. That means that I can continue sending the request to the chain successor as with nextHandler.call(e) or I can treat nextHandler as a function itself, nextHandler(e):
abstract class CellFormatter {
  CellFormatter nextHandler;

  void call(Event e) {
    if (_handleRequest(e)) return;
    if (nextHandler == null) return;

    nextHandler(e);
  }
  // ...
}
And, since the call() happens to have the correct signature for event listeners, I can supply the first object in the chain directly to the on-change listener:
  var textFormat = new TextFormatter();
  var dateFormat = new DateFormatter(textFormat);
  var numberFormat = new NumberFormatter(dateFormat);

  container.onChange.listen(numberFormat);
That reads much better—and it wasn't horrible to begin with! When the container sees a change event, it number formats the appropriate cell. The class code is similarly clear: when called, it either handles the request or calls the next successor. Wonderful!

I had thought about moving on from last night's "good enough" chain of responsibility. I am certainly glad I opted to linger a bit longer, this was a nice win. I do wonder if this is the gods' way of telling me to linger more often. Or maybe to call() more often. I'm sure one of those is the moral of this story.

Play with the code on DartPad: https://dartpad.dartlang.org/f5bbc86a28002987741c.


Day #101

Friday, February 19, 2016

Consequences of the Chain of Responsibility


Before wrapping up my initial research on the chain of responsibility pattern, I take one last look at the consequences of code that follows it. In particular, I would like to touch on configuration and maintainability tonight.

The example that I currently favor for illustrating the pattern is a set of cell formatting objects for a spreadsheet application:



To auto-format the cells, each formatting object in the chain is given an opportunity to claim responsibility for the content. In this example, a cell with all numbers is converted to a double with two digits after the decimal, a date is converted to ISO 8601 format, and everything else defaults to text.

To test configuration, I add some checkboxes to disable some of the formatters:



The main takeaway from this is that it is possible to easily change the chain of responsibility at runtime. The Dart listener for the no-text formatting checkbox might look like:
  query('#no-text').onChange.listen((e){
    var el = e.target;
    if (el.checked) {
      date.nextHandler = null;
    }
    else {
      date.nextHandler = text;
    }
  });
The date formatter normally points to the text handler. That is, if the date formatter thinks the current input field is not a date, then it forwards the request onto the text formatter. By ticking this checkbox, the date formatter now thinks that there is no next handler.

Thanks to last night's CellFormatter base class, this just works:
abstract class CellFormatter {
  CellFormatter nextHandler;

  void processRequest(Event e) {
    if (!isCell(e)) return;
    if (handleRequest(e)) return;
    if (nextHandler == null) return;

    nextHandler.processRequest(e);
  }
  // ...
}
With the checkbox ticked, the date formatter no longer has a nextHandler so the date formatter simply does nothing. The result in the UI is that a cell that was previously a numeric and was right-aligned retains the alignment because there is no longer a text formatter to reset it:



This illustrates another important aspect of the chain of responsibility. It is best to ensure that requests do not just "fall off" the end of the chain like this. Ideally, I ought to have a default handler at the end then resets all styles.

One last thing that I would like to touch on before calling it a day is how robust the pattern is in the face of change. Currently, the first formatter in the chain processes event requests when changes are seen in cells:
  container.onChange.listen(number.processRequest);
What if I also wanted to apply changes when clicks are seen inside cells? Well, aside from Dart's lack of an easy means to merge event streams, this is fairly easy to support.

I create a StreamController object and add events to it whenever there are clicks or changes:
  var c = new StreamController();
  container.onChange.listen(c.add);
  container.onClick.listen(c.add);
Then, I hand the first formatter in the chain to this combo-stream:
  c.stream.listen(number.processRequest);
And that's all there is to it. Now I can force formatting by tabbing to another cell or, if I am feeling impatient, I can click on a cell to format its contents.

Nice! That may finish my exploration of the chain of responsibility pattern in Dart (though there could be one more Darty trick to try). I do think this spreadsheet cell example will serve nicely in Design Patterns in Dart. The code is fairly simple, yet still feels like a real example, which is pretty close to ideal. Plus, it serves well when discussing some of the consequences of the pattern!

Play with the code on DartPad: https://dartpad.dartlang.org/08105c648b253f64a47d.


Day #100


Thursday, February 18, 2016

Delegated Events Chain of Responsibility


I came up with a simple DOM-based example of the chain of responsibility pattern last night. That might serve as an simple introduction to the pattern on the modern web, but I would prefer something with a little more heft to support subsequent discussions. So tonight, I attempt to apply the pattern to cell formatting object.

Given a bunch of cells in a table, I would like a series of objects to format input values correctly. Numbers should have 2 decimal places and be right-aligned. Dates should be iso8601 formatted and left aligned. Everything else should be treated as plain text and left aligned:



The handler in this chain of responsibility implementation is going to be a listener for change events on the container:
  container.onChange.listen(handler.processRequest);
I do not want a separate listener for each cell—that could wind up being a very large number of cells and listeners. Instead, I use a delegated events approach, listening on the container and filtering events based on the target.

The handler in this example will be the CellFormatter. As with any chain of responsibility implementation, the first thing that it needs is a way to specify the next link in the chain. In this case, the next handler:
abstract class CellFormatter {
  CellFormatter nextHandler;
  // ...
}
Next, I need to process events:
abstract class CellFormatter {
  // ...
  void processRequest(Event e) {
    if (!isCell(e)) return;
    if (handleRequest(e)) return;
    if (nextHandler == null) return;

    nextHandler.processRequest(e);
  }

  bool handleRequest(Event e) => false;
  // ...
}
First, I filter on cells (text input fields). Then I try to handle the current request. The default implementation here is for handleRequest to not handle the request, which it signals by returning false. It will be the job of the concrete subclasses to properly handle requests. If the request is not handled, then the request sent to the next object in the chain, if defined.

With that, I am ready to process different formatting, like NumberFormatter:
class NumberFormatter extends CellFormatter {
  bool handleRequest(Event e) {
    var input = e.target;
    RegExp exp = new RegExp(r"^\s*[\d\.]+\s*$");
    if (!exp.hasMatch(input.value)) return false;

    var val = double.parse(input.value);
    input.value = val.toStringAsFixed(2);
    input.style.textAlign = 'right';
    return true;
  }
}
If the current change event targets an input that does not match the numeric regular expression, handleRequest() returns false and the event is sent along to the next formatter object in the chain. If it does point to a numeric input element, the value is parsed and formatted with two digits after the decimal point. The text alignment of the input element is set appropriately for a numeric field. And that's it.

Other formatters follow similar approaches until the last item in the chain, the default text formatter. This formatter applies no formatting to the value, but ensures the left alignment of the field:
class TextFormatter extends CellFormatter {
  bool handleRequest(Event e) {
    var input = e.target;
    input.style.textAlign = 'left';
    return true;
  }
}
Armed with my formatters, I can create them in client code:
  var number = new NumberFormatter();
  var date = new DateFormatter();
  var text = new TextFormatter();
Then, I establish the successor chain:
  number.nextHandler = date;
  date.nextHandler = text;
That is all there is to it. Now when the event listener sends a request to the first item in the chain:
  container.onChange.listen(number.processRequest);
I know that one of the handlers will receive and process the event. I think that will be a reasonably accessible example for most readers. I may fiddle a bit more with the example tomorrow to be sure.

Play with the code on DartPad: https://dartpad.dartlang.org/21f67a92a0269a2aed6b.


Day #99

Wednesday, February 17, 2016

A DOM Chain of Responsibility


A major theme of the forthcoming Design Patterns in Dart is that design patterns are more useful for describing how systems are already designed, not for designing systems in the first place. The implications and applicability of patterns then aid programmers to understand how systems can evolve, once patterns are recognized in them.

With that in mind... consider a <div> with ID of "bottom" inside a <div> with ID of "middle" inside a <div> with ID of "top":



There are three Dart element objects:
  var bottom = query('#bottom'),
    middle = query('#middle'),
    top = query('#top');
If the bottom-most sees a request in the form of a click without modifier key, then it handles the request, preventing successors from seeing the request:
  bottom.onClick.listen((e){
    if (e.ctrlKey) return;
    if (e.shiftKey) return;

    bottom.style.border =
      bottom.style.border.contains('green') ?
        '' : '3px green dashed';
    e.stopPropagation();
  });
But if modifier key (shift or control) is held down while clicking in the middle of the "bottom" <div>, the request passes along to the successor. The next element object in line here is the "middle" <div>. If the request is received by this object with the shift key depressed, it handles the request, preventing successor from seeing the request:
  middle.onClick.listen((e){
    if (e.ctrlKey) return;

    middle.style.border =
      middle.style.border.contains('blue') ?
        '' : '3px blue dashed';
    e.stopPropagation();
  });
Finally, if it is not the control key, but the shift key that is depressed while clicking the "bottom" element, the request passes through both the bottom handler and the middle handler—both of which opt not to handle the request. In this case, the request is finally handled by top:
  top.onClick.listen((_){
    top.style.border =
      top.style.border.contains('orange') ?
        '' : '3px orange dotted';
  });
So is this a chain of responsibility pattern? Of course! There are concrete handler objects all of the same type. They all declare the same method to process a request object. The method may be in the form of an event listener instead of a pure method, but the overall intent and structure is the same. This is a chain of responsibility—and one that just about every web developer implemented at some point without thinking about the pattern.

And the implications and applicability? Well, that's a tale for another day.

Play with the code on DartPad: https://dartpad.dartlang.org/12bf7fa9c76c6d16fe5f.


Day #98

Tuesday, February 16, 2016

In Which I Take Things One Step Too Far...


So the chain of responsibility pattern in Dart… I've explored it with noSuchMethod(). I've explored it with mixins. But I have yet to explore it with noSuchMethod() in mixins.

Things are gonna get a little crazy tonight.

I continue to work with the _PurchasePower mixin for employee-like classes. It describes the ability of an employee to make purchasing decisions. It sets the successor in the responsibility chain to point to the employee next on the corporate ladder:
abstract class _PurchasePower {
  get successor => reportsTo;
  // ...
}
In this case, it simply delegates to the reportsTo property of Employee—the receiver of the mixin.

The _PurchasePower mixin completes the chain of responsibility pattern by declaring processRequest(). This method sends the request to the successor if the current class does not handle it, and _processRequest(), which performs the actual handling of the request:
abstract class _PurchasePower {
  // ...
  void processRequest(PurchaseRequest request) {
    if (_processRequest(request)) return;
    if (successor == null) return;

    successor.processRequest(request);
  }

  bool _processRequest(_) => false;
}
That works great when there is only one request to handle, but what if there are multiple requests to be handled (e.g. processorName() and processRequest())?

This is where it would be handy to be able to mixin noSuchMethod(). Instead of declaring processRequest() to possibly send the request to the successor, noSuchMethod() can do so. Except I hit a stumbling block right away here.

First, I need to handle requests by converting processRequest() to _processRequest() and processorName() to _processorName(). Just prepend an underscore, right? Well, no.

When I get the arguments inside noSuchMethod, I can figure out the method that was being invoked by checking memberName. From here, it should be a simple matter of interpolating noSuchMethod's memberName into a string:
  noSuchMethod(args) {
    var handlerMethod = "_${args.memberName}";
    // ...
  }
The problem is that memberName is a Symbol, which gets converted to strings as "Symbol('symbol_name_here'). So the handlerMethod winds up being _Symbol('_processRequest'). Not at all what I want.

I have two undesirable choices here—strip Symbol(' and ') from the resulting string or painstakingly lookup the string value. Neither is a good option, but the latter seems to be the most official way:
  noSuchMethod(args) {
    var handlerMethod = "_${MirrorSystem.getName(args.memberName)}";
    // ...
  }
Yuck. And unfortunately, I am not done with the yuck. I cannot invoke methods with strings, so I have to convert that back to a Symbol:
  noSuchMethod(args) {
    Symbol handlerMethod = new Symbol("_${MirrorSystem.getName(args.memberName)}");
    // ...
  }
Even now, I am not done with the yuck. And this next yuckiness takes me a while to track down.

It turns out that you cannot use the Symbol constructor to create a symbol that is private. Well, that is not 100% true, it lets me create a symbol, but I am not allowed to use it to invoked the private method. Making this situation even more annoying is that I can invoke _processRequest() with a symbol literal: #_processRequest. But if I dynamically try to create that symbol, it silently fails to call the right method.

Bummer.

Even if I choose a different naming convention, I would not want the method that actually processes the request to be public. Only the method invoking the handler or sending the request to the successor should be public. So I am left to either move handler code into noSuchMethod() to sit beside the successor code or I can give the handler method a weird name.

I opt for the latter by prepending xxx_ to the name:
  noSuchMethod(args) {
    Symbol handlerMethod = new Symbol("xxx_${MirrorSystem.getName(args.memberName)}");
    // ...
  }
With this approach, I eventually get the code working, but... yuck.

Even if this were back in the Employee class, I would still face the same limitation from the Symbol constructor. In other words, this seems like an ill-advised approach in current Dart.

Play with the code on DartPad: https://dartpad.dartlang.org/9f9ca7397d88f6cf7e54.



Day #97