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

Monday, February 15, 2016

How Much Mixin for the Chain of Responsibility?


After last night, I am again a fan of mixins in Dart. Mixins will not solve all problems, but they seem to solve several cases of chain of responsibility pattern nicely. I still have some follow-up questions, though. Up tonight how much of the chain can I get into the mixin class (and how much should I get in there)?

The mixin in my current example adds purchasing power traits to an Employee class. Give that Employee supports a reportsTo property, the _PurchasingPower mixin delegates the chain of reponsibility's successor to this property:
abstract class _PurchasePower {
  get successor => reportsTo;
  // ...
}
If the handler method in the chain is unable to process the current request, it will forward it along to this property. For a manager, this property might point to a director. For a director, it might point to a VP.

As for handling the request, I currently do that via two methods:
abstract class _PurchasePower {
  // ...
  void processRequest(PurchaseRequest request) {
    if (_processRequest(request)) return;
    if (successor == null) return;

    successor.processRequest(request);
  }

  bool _processRequest(_) => false;
}
The processRequest() method is responsible for the successor chain while _processRequest() is responsible for attempting to handle the actual request. The default implementation in the mixin is for _processRequest() to not handle the request. In practice, concrete handler classes are expected to override this behavior.

I appreciate the separation of focus between the two methods. It is nice that subclasses only have to worry about overriding the processing of the request instead of handling the request and managing the successor chain. When _PurchasePower is mixed into the Manager class, for instance, it is completely unaware of the chain of responsibility:
class Manager extends Employee with _PurchasePower {
  final double _allowable = 10 * 1000.0;

  bool _processRequest(PurchaseRequest request) {
    if (request.amount > _allowable) return false;

    print("Manager will approve $request.");
    return true;
  }
}
It either handles the request or it does not. Simple.

And yet, I note that the manner in which it handles the request is very similar to the manner in which the Director class handles the same request:
class Director extends Employee with _PurchasePower {
  final double _allowable = 20 * 1000.0;

  bool _processRequest(PurchaseRequest request) {
    if (request.amount > _allowable) return false;

    print("Director will approve $request");
    return true;
  }
}
The only thing that varies in the implementation of _processRequest() is the name of the employee that potentially has the appropriate purchasing power. The Employee base class can figure this out from the runtime type of the object:
class Employee {
  // ...
  String get title => "${this.runtimeType}";
  String toString() => title;
}
By defining the toString() method, I tell Dart how to interpolate this object into any string. Making use of that in the _PurchasePower mixin, I can declare a common _processRequest() handler method as:
abstract class _PurchasePower {
  final double _allowable = 0.0;
  // ...
  bool _processRequest(PurchaseRequest request) {
    if (request.amount > _allowable) return false;

    print("$this will approve $request.");
    return true;
  }
}
My _PurchasePower chain of responsibility mixin is getting crowded now. That said, the payoff is pretty nice. The employee subclasses with purchasing power now only need to declare the maximum allowed amount that they can handle:
class Manager extends Employee with _PurchasePower {
  final double _allowable = 10 * 1000.0;
}

class Director extends Employee with _PurchasePower {
  final double _allowable = 20 * 1000.0;
}

class VicePresident extends Employee with _PurchasePower {
  final double _allowable = 40 * 1000.0;
}
The mixin takes care of both processing the request and handling the successor chain. Even with this wonderfully compact implementation, I still retain the ability to override the default behavior as when the President always halts the chain:
class President extends Employee with _PurchasePower {
  final double _allowable = 60 * 1000.0;

  void processRequest(PurchaseRequest request) {
    if (request.amount > _allowable) {
      print("Your request for $request needs a board meeting!");
    }
    else {
      print("President will approve $request");
    }
  }
}
Since there is no successor beyond President I override the processRequest() method, handling the request directly.

And yes, the chain of responsibility still works as desired:
$ ./bin/purchase.dart 2000 
Manager will approve $2000.00 for General Purpose Usage.
$ ./bin/purchase.dart 12000
Director will approve $12000.00 for General Purpose Usage.
$ ./bin/purchase.dart 22000
VicePresident will approve $22000.00 for General Purpose Usage.
$ ./bin/purchase.dart 52000
President will approve $52000.00 for General Purpose Usage
$ ./bin/purchase.dart 82000
Your request for $82000.00 for General Purpose Usage needs a board meeting!
So the answer to tonight's question would seem to be that, if the process handler is sufficiently generic, I can put everything into the chain mixin. The resulting concrete handler implementations are wonderfully succinct. There is barely any readability cost in the mixin class in this example thanks to Dart's toString() method. And I still retain the ability to override behavior in subclasses should that be required. Certainly this will not always be possible, but when there is sufficiently common process handling, this is a nice little code win.

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


Day #96

Sunday, February 14, 2016

The Chain of Responsibility is Better with Mixins


Having spent the entirety of last night's post lamenting the practice of using pattern-specific naming conventions, tonight I… use some pattern specific naming conventions. Well, maybe.

Tonight, I try out mixins as a possible implementation for the chain of responsibility pattern. I am unsure how it will work, but before trying it, it seems as though I will need to use patterns names in the mixin class.

Something that I hope to explore in Design Patterns in Dart are Dart twists on design patterns. On classic OO patterns, that should involve mixins. That said, the main reason that I think mixins might be appropriate in this case is that the example that I adapted from the Wikipedia pages bothers me:
  var manager = new ManagerPurchasePower();
  var director = new DirectorPurchasePower();
  var vp = new VicePresidentPurchasePower();
  var president = new PresidentPurchasePower();
I realize that this is example code, but I am hard-pressed to think that I would ever code up objects named "purchasing power." It seem much more likely that I would create Manager, Director, etc. classes with purchasing power traits. Hence, the thinking that mixins might be a good solution.

A more real-world example, I think, would be an Employee class:
class Employee {
  String firstName, lastName;
  Employee reportsTo;
}
The Manager, Director classes would then extend this class:
class Manager extends Employee {
  // Manager specializations here...
}
class Director extends Employee {
  // Director specializations here..
}
// ...
In this scenario, a purchasing power chain of responsibility can be described with:
abstract class _PurchasePower {
  get successor => reportsTo;

  void processRequest(PurchaseRequest request) {
    if (_processRequest(request)) return;
    if (successor == null) return;

    successor.processRequest(request);
  }

  bool _processRequest(_) => false;
}
The successor in this chain is delegated to the reportsTo property of Employee. I could also have replaced subsequent references to successor with reportsTo and the code would have remained equally readable. I opt to stick with the pattern participant name (successor) as a default starting point. The domain naming convention from last night may very well prove more maintainable. Then again, since this mixin class exists solely to implement the chain of responsibility pattern, perhaps its domain is really the pattern itself. Unsure, I opt for the pattern name for now.

In handle-request method, I first try to process the request with a subclass overrideable _processRequest() method. If the subclass' _processRequest() handles the request, it returns true, breaking the chain. If the subclass' implementation returns false (or the default implementation is invoked), then the next item in the chain is asked to handle the request.

Armed with this _PurchasePower class, I can mix it into the subclasses of Employee with the with keyword:
class Manager extends Employee with _PurchasePower {
  final double _allowable = 10 * 1000.0;

  bool _processRequest(PurchaseRequest request) {
    if (request.amount > _allowable) return false;

    print("Manager will approve $request.");
    return true;
  }
}
For the Manager class, the purchasing power traits are expressed by the overridden _processRequest() method. If the purchase request amount is more than $10,000, then the manager is unable to approve the request. The chain of responsibility is then passed back to the processRequest() method in the _PurchasePower mixin. In that case the successor / reportsTo is then asked to handle the request.

The successor chain is expressed in the Employee class, though technically it is only in the _PurchasePower mixin that this relationship recognized as a chain. The actual relationship is established in client code (alternatively, last night's solution can establish the relationship in the classes):
  var manager = new Manager();
  var director = new Director();

  manager.reportsTo = director;
Although I remain unsure of some of the specifics like naming, I very much appreciate this mixins approach. In hindsight, the original class names (e.g. ManagerPurchasingPower) were probably screaming at me that a mixin was trying to escape from my code. Regardless, encapsulating the pattern entirely in a mixin class while limiting Employee subclasses to employee-specific responsibilities feels like clean, maintainable code. So this feels very much like a win.

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


Day #95

Saturday, February 13, 2016

Wacky Successor Chain of Responsibility


Let's talk about the successor chain in the chain of responsibility pattern. In the purchasing power example that I have been using so far, the handler maintains responsibility for defining new links via a successor setter method:
abstract class PurchasePower {
  PurchasePower _successor;
  void set successor(PurchasePower successor) {
    _successor = successor;
  }
  // ...
}
This required client code to establish the links between instances:
  var manager = new ManagerPurchasePower();
  var director = new DirectorPurchasePower();
  var vp = new VicePresidentPurchasePower();
  var president = new PresidentPurchasePower();

  manager.successor = director;
  director.successor = vp;
  vp.successor = president;
I am OK with the approach here, but I am not a fan of the name successor. Really, in general, I am not a fan of using pattern names or participants in patterns—not even in examples. I much prefer domain specific names that are optionally annotated with pattern names.

In the case of organization purchase power, the successor would be better expressed as reports to / direct reports relationships:
abstract class PurchasePower {
  // Successor in the chain of responsibility
  PurchasePower _reportsTo;
  void set reportsTo(PurchasePower reportsTo) {
    _reportsTo = reportsTo;
  }
  // ...
}
Now when I look at the chain of responsibility being established, there is less mental translation between design pattern naming and the current domain:
  var manager = new ManagerPurchasePower();
  var director = new DirectorPurchasePower();
  var vp = new VicePresidentPurchasePower();
  var president = new PresidentPurchasePower();

  manager.reportsTo = director;
  director.reportsTo = vp;
  vp.reportsTo = president;
Everything about this feels more comfortable. Maybe there are people out there that look at a problem, tap their chin while considering things until finally shouting, "a-ha! the chain of responsibility will work here!" For me, the relationship comes first, after which I might come up with an approach to decide which member in the relationship needs to handle things. Then, if I am really paying attention, I might even think "ooh, that's the chain of responsibility!"

Hopefully if I keep plugging away at these patterns, I will get to the point at which they are more recognizable in situations like this. But I seriously doubt I will ever get to the chin-tapping state. And I am unsure that I would ever want to. I think the code is more maintainable with the domain names instead of the pattern names (and really, no one ever liked classes named abstract factory factory).

But I digress.

Another possible approach to the chain of responsibility is to exploit either the data structure in use or the domain. There is not really a data structure in play with this example, but the domain certainly implies a hierarchy—a manager will always report to a director, who will always report to a VP, etc. I can exploit that to eliminate the explicit assignment of reportsTo properties.

I start with a static mapping of runtime types pointing to the last used instance of that type:
abstract class PurchasePower {
  static Map<Type, PurchasePower> _instances = {};
  PurchasePower() {
    _instances[this.runtimeType] = this;
  }
  // ...
}
Any subclass of the PurchasePower handler will invoke the constructor here, caching the last instance of the give type. That is, when a ManagerPurchasePower instance is created, this superclass constructor will be called storing the instance index by the type.

The DirectorPurchasePower constructor can then make use of this, finding the most recent ManagerPurchasePower and assigning this instance as the reportsTo:
class DirectorPurchasePower extends PurchasePower {
  // ...
  DirectorPurchasePower() : super() {
    _directReport(ManagerPurchasePower);
  }
  // ...
}
After setting the default successor chain like this in the VP and President purchase power classes, I no longer have to explicitly specify the chain of responsibility. I simply create the various instances, start with the lowest and see which claims responsibility along the way:
  var manager   = new ManagerPurchasePower();
  var director  = new DirectorPurchasePower();
  var vp        = new VicePresidentPurchasePower();
  var president = new PresidentPurchasePower();

  var req = new PurchaseRequest(25*1000, "General Purpose Usage");
  manager.processRequest(req);
This particular recent instance storage and lookup implementation feels a little forced. Explicitly setting the chain was not too horrible and this approach is non-trivial. Still, it was good to explore the successor chain in a little more depth.

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


Day #94

Friday, February 12, 2016

Chain of Responsibility, but with noSuchMethod


Most of the fun of the chain of responsibility pattern is building the chain. One of the implementations suggested in the Gang of Four book involves Smalltalk's doesNotUnderstand. In Dart, that means it is time for some noSuchMethod() fun.

In the purchasing power example that I adapted from Wikipedia, the handler currently supports the chain with:
abstract class PurchasePower {
  PurchasePower _successor;
  void set successor(PurchasePower successor) {
    _successor = successor;
  }

  void processRequest(PurchaseRequest request) {
    if (_successor != null) {
      _successor.processRequest(request);
    }
  }
}
If a concrete handler sets the successor, then the processRequest() method in this handler base class will forward the request on to the next handler in the chain.

For example, the manager-level purchasing power handler will handle requests for less than $10k:
class ManagerPurchasePower extends PurchasePower {
  final double _allowable = 10 * 1000.0;

  void processRequest(PurchaseRequest request) {
    if (request.amount < _allowable) {
      print("Manager will approve $request.");
      return;
    }
    super.processRequest(request);
  }
}

If the request is for more, then the superclass implementation of processRequest() is invoked, passing the request along to the next object in the chain. The nice thing about this approach is that a subclass that does not want to handle a request can simply omit a declaration of processRequest(), allowing the superclass to forward the request on to the chain successor.

So what does noSuchMethod() buy me in this scenario? Not a ton, but it does yield a more generalized approach to handling requests. In the baseclass, I replace the previous processRequest() with:

import 'dart:mirrors' show reflect;
abstract class PurchasePower {
  // ...
  noSuchMethod(args) {
    if (_successor == null) return;
    reflect(_successor).delegate(args);
  }
}

If a concrete class does not define a method like processRequest() (or invokes it directly in the superclass), then the invocation winds up in noSuchMethod(). If there is no successor in the chain, then nothing is returned, terminating the chain. Otherwise, thanks to the magic of delegate(), the successor is reflected so that the method being invoked can be sent to the successor along with any arguments.

With that, when processRequest() in concrete handlers invokes the method of the same name in the superclass, noSuchMethod() kicks in, forwarding the request along to the successor. The behavior is exactly the same as with an explicit processRequest() in the superclass, only noSuchMethod() will work with any method, instead of a single method.

So, in the end, I don't know that this buys me much, except when multiple handlers are involved. Or when one simply wants to have fun with mirrors.

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

Day #93

Thursday, February 11, 2016

The Chain of Responsibility Pattern in Dart


How can anyone not love a pattern named chain of responsibility? I mean c'mon, the name invokes all sorts of linked interaction between objects that somehow manage to cooperate on ownership for an action of some sort. It's the kind of thing that makes bureaucracy so awful, but there's a pattern in programming that makes it elegant. So what's not to love?

I start my investigation of the pattern as I so often do, by copying the Java example on the Wikipedia page into lovely Dart code. The prime mover in the pattern—the interface used by the outside world—is the handler. It gets its name, as one might suspect, from its job to… handle a request (and then optionally forward the request on). The handler in the Wikipedia example describes purchasing power.

In Dart, the purchasing power interface looks like:
abstract class PurchasePower {
  PurchasePower _successor;
  void set successor(PurchasePower successor) {
    _successor = successor;
  }

  void processRequest(PurchaseRequest request);
}
The "chain" portion of this pattern is handled by the _successor private variable. If this PurchasePower class does not want to handle the request, the _successor is specified as the next in the chain. The processRequest() method holds the responsibility for handling the request. It receives a purchase request and must decide to handle it or forward the request on to the _successor.

The lowest level of purchasing power in the example is that of a lowly manager:
class ManagerPurchasePower extends PurchasePower {
  final double _allowable = 10 * 1000;

  void processRequest(PurchaseRequest request) {
    if (request.amount < _allowable) {
      print("Manager will approve $request.");
    }
    else if (_successor != null) {
      _successor.processRequest(request);
    }
  }
}

The upper limit that a manager can approve of is $10,000. If the request is for less than that, then the chain ends with the approval by the manager. If it is more than that, then the _successor is then asked to process the same request.

The object being processed by the pattern's handler is a purchase request:

class PurchaseRequest {
  double amount;
  String purpose;
  PurchaseRequest(this.amount, this.purpose);
  String toString() =>
    "\$${amount.toStringAsFixed(2)} for $purpose";
}

It requires a dollar amount and a description of the reason for the purchase. I provide a toString() method so that the entire object can be interpolated in a string (as it is when the manager approves the request).

That is the whole of the pattern. For it to be a true chain, I declare director, VP and presidential purchasing power. Anything that the president, who will be last in succession, cannot purchase needs board approval and not another successor:

class PresidentPurchasePower extends PurchasePower {
  final double _allowable = 60 * 1000;

  void processRequest(PurchaseRequest request) {
    if (request.amount < _allowable) {
      print("President will approve $request");
    }
    else {
      print("Your request for $request needs a board meeting!");
    }
  }
}
In client code, I can create each of these purchasing power objects:
  var manager = new ManagerPurchasePower();
  var director = new DirectorPurchasePower();
  var vp = new VicePresidentPurchasePower();
  var president = new PresidentPurchasePower();
Then I can specify the chain:
  manager.successor = director;
  director.successor = vp;
  vp.successor = president;
Lastly, I can parse the dollar amount being requested and start the chain on its merry path:
  var amount = (args[0] == null) ?
    1000 : double.parse(args[0]);

  var req = new PurchaseRequest(amount, "General Purpose Usage");
  manager.processRequest(req);
With that, I can quickly determine who to bug for the new company automobiles (including my Tesla):
$ ./bin/purchase.dart 5000 
Manager will approve $5000.00 for General Purpose Usage.
$ ./bin/purchase.dart 10000
Director will approve $10000.00 for General Purpose Usage
$ ./bin/purchase.dart 20000
Vice President will approve $20000.00 for General Purpose Usage
$ ./bin/purchase.dart 50000
President will approve $50000.00 for General Purpose Usage
$ ./bin/purchase.dart 75000
Your request for $75000.00 for General Purpose Usage needs a board meeting!

That was a nice start to exploration of the chain of responsibility pattern. I am already looking forward to kicking the tires on this pattern a little more.

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

Day #92

Wednesday, February 10, 2016

Factory Method Pattern and Polymer Paper Elements


I may regret this, but my web-based factory method pattern example lacked a "modern" touch. Well, that's not entirely true, it could add relatively new input elements like number, telephone, and week inputs to a form:



But darn it, what about awesome Paper Elements? Will a <paper-input> element serve as a product of the pattern? It sure would be neat if I could simply drop it into the pattern without many changes.

But alas, it seems that some changes are going to be required. Even though it behaves like an input field, the PaperInput class implements HtmlElement, not InputElement like my FormBuilder class wants:
abstract class FormBuilder {
  // ...
  void addInput() {
    var input = _labelFor(inputElement);
    container.append(input);
  }
  InputElement get inputElement;
  // ...
}
The factory method in this example is the inputElement getter, which returns an InputElement. Because of the PaperElement inheritance, I have to change that to return the more general HtmlElement:
abstract class FormBuilder {
  // ...
  HtmlElement get inputElement;
  // ...
}
How many other changes am I going to have to make?

Well, I certainly have to list Polymer as a dependency in my project's pubspec.yaml. To get <paper-input>, I need paper_elements as well:
name: factory_method_code
dependencies:
  polymer: ">=0.15.1 <0.17.0"
  paper_elements: ">=0.7.0 <0.8.0"
transformers:
- polymer:
    entry_points:
    - web/index.html
Next, I have to import the paper element into the containing page:
<!doctype html>
<html lang="en">
  <head>
    <!-- ... -->
    <link rel="import" href="packages/paper_elements/paper_input.html">
    <script type="application/dart" src="input_factory.dart"></script>
  </head>
  <body><!-- ... --></body>
</html>
I have to do the same with the backing code in the input_factory.dart script:
import 'package:polymer/polymer.dart';
import 'package:paper_elements/paper_input.dart';

abstract class FormBuilder {
  // ...
}
// Concrete factories here...
The final Polymer-y thing that needs to happen is an initPolymer() call in my main() entry point, also in the input_factory.dart script:
main() async {
  await initPolymer();
  // Start up the factory code once Polymer is ready...
}
That's it for the Polymer preliminaries. Now what needs to change in the pattern itself to accommodate PaperInput? Mercifully, not much. In the RandomBuilder class, which is a concrete factory implementation of the FormBuilder, I add a new random option (#5) for PaperInput:
class RandomBuilder extends FormBuilder {
  RandomBuilder(el): super(el);
  Element get inputElement {
    var rand = new Random().nextInt(7);

    if (rand == 0) return new WeekInputElement();
    if (rand == 1) return new NumberInputElement();
    if (rand == 2) return new TelephoneInputElement();
    if (rand == 3) return new UrlInputElement();
    if (rand == 4) return new TimeInputElement();
    if (rand == 5) return new PaperInput();

    return new TextInputElement();
  }
}
Unfortunately, I also have to make a change in the superclass. Previously, when all of the products were InputElement instances, I could count on them supporting the type property (e.g. telephone, number, time), which I could use as a default text label on the page:
abstract class FormBuilder {
  // ...
  _labelFor(el) {
    var text = el.type;
    var label = new LabelElement()
      ..appendText("$text: ")
      ..append(el);

    return new ParagraphElement()..append(label);
  }
}
That will not work for PaperInput, which does not support the type property. If I had control of the product classes, I could force PaperInput to support type. Since that is not possible, I either have to create wrapper classes or, more easily, add an object type test for InputElement:
abstract class FormBuilder {
  // ...
  _labelFor(el) {
    var text = (el is InputElement) ? el.type : el.toString();
    // ...
  }
}

By itself, that one line is not too horrible. That said, I can imagine things going quickly off the rails here by adding a non-InputElement into the mix. For a limited use case like this example, however, it works.

In the end, it was fairly easy to get a PaperInput element added to the mix of my InputElement factory method. Most of the effort was the usual Polymer overhead. The resulting interface mismatch likely will not cause too much trouble in this case, but could get ugly quickly in other scenarios.

Day #91

Tuesday, February 9, 2016

A Nearly Modern Factory Method Pattern


I could make do with the examples of the factory method pattern that I have been using. Still, I would prefer an example that touches the modern web a little closer. Or at least the web. So tonight I try my hand at a venerable, if simple, form builder.

I am not going to worry too much about the details of adding different types of HTML form inputs at this point. To kick things off, I start by adding variations of text input fields to a container. So my Dart abstract creator class declares that it needs to be constructed with a container element:
abstract class FormBuilder {
  Element container;
  FormBuilder(this.container);
}
Next, I declare an addInput() method that will append an input field to the container:
abstract class FormBuilder {
  // ...
  void addInput() {
    var input = _labelFor(inputElement);
    container.append(input);
  }
  // ...
}
The _labelFor() helper method is unimportant in this discussion. It merely adds a text label to the input element. What is important here is the inputElement property. That is going to be the factory method in the factory method pattern. It lacks the usual trailing parentheses because it will be a getter method:
abstract class FormBuilder {
  // ...
  InputElement get inputElement;
  // ...
}
It lacks a method body because the definition of what inputElement does will have to come from subclasses.

Putting these all together, I have a prototypical "creator" in the factory method pattern:
abstract class FormBuilder {
  Element container;
  FormBuilder(this.container);
  void addInput() {
    var input = _labelFor(inputElement);
    container.append(input);
  }
  InputElement get inputElement;
  // ...
}
It declares a factory method, inputElement, and an operation that uses that factory, addInput(). The creator in the classic factory method pattern is an interface for concrete implementations.

For a first pass at a concrete creator class, I declare a RandomBuilder class. As the name implies, the inputElement factory method randomly chooses from a selection of input element types:
import 'dart:math' show Random;

class RandomBuilder extends FormBuilder {
  RandomBuilder(el): super(el);
  InputElement get inputElement {
    var rand = new Random().nextInt(6);

    if (rand == 0) return new WeekInputElement();
    if (rand == 1) return new NumberInputElement();
    if (rand == 2) return new TelephoneInputElement();
    if (rand == 3) return new UrlInputElement();
    if (rand == 4) return new TimeInputElement();
    return new TextInputElement();
  }
}
The other piece of the pattern is the "product." The product in this case the standard InputElement from dart:html — nobody ever said that the product had be a hand-coded class, after all. Given that, the concrete products are the various types of input elements that are randomly returned from the getter factory method.

And there you have it: a simple, web implementation of the factory method pattern!

I can use this in client code by creating a new form builder element as part of a button click handler:
  var button = new ButtonElement()
    ..appendText('Build Input')
    ..onClick.listen((_){
        new RandomBuilder(container).addInput();
      });
This might be a little too simplistic, but I rather like the example. It feels accessible for most web developers. It could also serve as a building block for further examples. I may continue to explore slightly more modern examples tomorrow, though other patterns beckon. Stay tuned!


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


Day #90

Monday, February 8, 2016

Silly Factories in the Factory Method Pattern


Tonight, I look into using Dart factory constructors in the factory method pattern. Since they both have the word "factory" in them they can probably be used together, right? Well, probably not, but I can no longer resist pairing the two.

Normal generative constructors in Dart behave like constructors in just about any object-oriented language. They create a new instance of the current class, optionally setting some instance variables. Factory constructors, on the other hand, are responsible for building and initializing the object being created. This means that factory constructors can return anything—not limited to the current class.

Take, for instance, a Person class:
class Person {
  int age;
  Person(this.age);
}
When a new Person is instantiated with new Person(21), the generative constructor creates an instance of Person and assigns the age instance variable to 21. Easy peasy.

Now I introduce two subclasses (both still using plain-old generative constructors):
class Child extends Person {
  Child([age=12]) : super(age);
}

class Adult extends Person {
  Adult([age=18]) : super(age);
}
There is nothing special here. Both classes default to an age appropriate for the type of person being created. What these allow me to do is declare a (named) factory constructor back in Person:
class Person {
  factory Person.random() => 
    new Random().nextBool() ? new Child() : new Adult();
}
This Person.random() constructor creates and returns full-blown object. It cannot rely on the language to generate the object, instead it has to do all of the work itself. With that, I can randomly generate children and adults from the Person superclass:
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Child'
What is really weird about these factory constructors is that they do not have to return an instance of the current class or a subclass. Instead, I can declare a Person constructor that returns a string:
class Person {
  // ...
  factory Person.string() { return "A person"; }
}
And that works perfectly fine:
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Child'
  new Person.string();
  // => 'A person'
To be completely honest, that is not "perfectly fine." The Dart type analyzer does complain:
[warning] The return type 'String' is not a 'Person', as defined by the method 'string'
But despite the warning, the code compiles and runs (see this DartPad).

Anyhow, back to the task at hand. How can I use these factory constructors in the factory method pattern? Well, I probably cannot since one is a constructor and the other a method, but let's do it anyway. I currently have a GameFactory class that creates a bunch of different board game products:
class GameFactory {
  // ...
  // The factory method
  createBoardGame([String game]) {
    if (game == 'Checkers') return new CheckersGame();
    if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
    return new ChessGame();
  }
}
Instead of a factory method, I can use a factory constructor:
class GameFactory {
  // ...
  factory GameFactory.createBoardGame([String game]) {
    if (game == 'Checkers') return new CheckersGame();
    if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
    return new ChessGame();
  }
}
Since BoardGame is not a subclass of GameFactory, the Dart type analyzer complains something fierce about this. But it compiles and runs anyway:
  new GameFactory.createBoardGame('Checkers').play();
  new GameFactory.createBoardGame('Thermo Nuclear War').play();
  new GameFactory.createBoardGame().play();
So what does this buy me? Like war, absolutely nothing.

In fact, I lose the ability to associate the factory constructor board games with the rest of the series. Each of those three board games are completely independent of the game factory series, which can no longer keep a reference to each for a final score:
  var series = new GameFactory('Professor Falken', 'Joshua');
  series.start();

  new GameFactory.createBoardGame('Checkers').play();
  new GameFactory.createBoardGame('Thermo Nuclear War').play();
  new GameFactory.createBoardGame().play();
So in the end, factory constructors and the factory method pattern are amusing together, but I can see no practical benefit. It was still totally worth messing around with them though!

Play with the amusing code on DartPad: https://dartpad.dartlang.org/4a59d56472d11cde9354.


Day #89

Sunday, February 7, 2016

Factory Games with Mirrors


Up tonight I finally carry through on my threat to apply mirrors to the factory method pattern in Dart. I am unsure if my beloved mirrors can have their usual improving effect (in my eyes at least), but I am always happy to have an excuse to play with reflection and mirrors.

Tonight's excuse comes in the form of the language specific implementations mentioned in the Gang of Four book. They mentioned that factory methods in Smalltalk often return the class to be created instead of an object. Aside from having to import the dart:mirrors library, it is not much more difficult to do the same thing in Dart.

The prime mover in the factory method pattern is the creator class. In the "game factory" example with which I have been toying, the GameFactory class creates a series of games between two players, then allows them chose any number of board games to play. The returns-a-class version might look something like:
// Creator
class GameFactory {
  String playerOne, playerTwo;
  GameFactory(this.playerOne, this.playerTwo);
  // ...

  // The factory method
  Type boardGameClass([String game]) {
    if (game == 'Checkers') return CheckersGame;
    if (game == 'Thermo Nuclear War') return ThermoNuclearWar;
    return ChessGame;
  }
}
That will force the client code to reflect on the classes, which is an obnoxious thing to ask of client code. So instead, I import dart:mirrors and return a class mirror from the boardGameClass() method:
import 'dart:mirrors' show reflectClass, ClassMirror;

// Creator
class GameFactory {
  // ...
  ClassMirror boardGameClass([String game]) {
    if (game == 'Checkers') return reflectClass(CheckersGame);
    if (game == 'Thermo Nuclear War') return reflectClass(ThermoNuclearWar);
    return reflectClass(ChessGame);
  }
}
Let's take a look at the resulting client code next. When it worked directly with objects, the client code looked like:
main() {
  var series = new GameFactory('Professor Falken', 'Joshua');
  series.start();

  var game;
  game = series.createBoardGame('Checkers');
  game.play();

  game = series.createBoardGame('Thermo Nuclear War');
  game.play();

  // Defaults to a nice game of chess
  game.createBoardGame();
  game.play();
}
That is pretty simple: start by creating a game factory instance, then create a game / play the game, create a game / play a game, etc.

With mirrors, the code now becomes:
main() {
  var series = new GameFactory('Professor Falken', 'Joshua');
  series.start();

  var game;
  game = series.
    boardGameClass('Checkers').
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();

  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();

  // Defaults to a nice game of chess
  game = series.
    boardGameClass().
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();
}
Look, I love mirrors more than just about anyone, but even I have to admit that is horrible. There is far too much noise obscuring the relatively simple intent of the code. I am not a fan of being forced to supply a constructor as a Symbol—it seems like the default constructor could be inferred (I'm sure there is a good reason it is not though). Similarly, I do not like being forced to supply an empty list of arguments to the newInstance() constructor method. But the truth is, even if both of those complaints went away, the newInstance() and reflectee calls would still make a mirror approach significantly less desirable than the plain-old object approach.

So mirrors are always undesirable in the factory method pattern, right? Well, not so fast. If there is a situation in which the client might want to create products with varying constructor arguments, then this mirror approach could come in handy. For instance, if we want to teach Joshua about thermonuclear war, we can create a alternate constructor for assigning different starting values for the two players:
class ThermoNuclearWar extends BoardGame {
  List playerOnePieces = [ '1,000 warheads' ];
  List playerTwoPieces = [ '1,000 warheads' ];
  ThermoNuclearWar(): super();
  ThermoNuclearWar.withWarheads(this.playerOnePieces, this.playerTwoPieces);
  String get winner => "None";
}
The client code can then run through as many scenarios as it takes to teach that thermonuclear war is a very strange game indeed:
  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();

  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(
      new Symbol('withWarheads'),
      [['1 warhead'], ['1 warhead']]
    ).
    reflectee;
  game.play();

  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(
      new Symbol('withWarheads'),
      [['1 warhead'], ['1,000 warheads']]
    ).
    reflectee;
  game.play();
This would result in output like:
$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***

  ThermoNuclearWar
    Player One starts with: 1,000 warheads
    Player Two starts with: 1,000 warheads
    --
    Winner: None

  ThermoNuclearWar
    Player One starts with: 1 warhead
    Player Two starts with: 1 warhead
    --
    Winner: None

  ThermoNuclearWar
    Player One starts with: 1 warhead
    Player Two starts with: 1,000 warheads
    --
    Winner: None
Afterwards, the game series can then switch back to a nice game of chess:
  // Defaults to a nice game of chess
  game = series.
    boardGameClass().
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();
So there is a reason for using mirrors in the factory method pattern after all. Yay! That said, they do not make as much sense as returning classes in Smalltalk. I will have to continue my search for Dart-specific features that can be brought to bear on the factory method pattern tomorrow.

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


Day #88

Saturday, February 6, 2016

I've Got a Factory in My Factory in My Class Hierarchy of Factories (or Something Like That)


Yesterday I worked up a Dart example of the factory method pattern in which a "game factory" could pit two players against each other in a series of board games:
main() {
  var series = new GameFactory('Professor Falken', 'Joshua');

  series
    ..start()
    ..createBoardGame('Checkers').play()
    ..createBoardGame('Thermo Nuclear War').play()
    ..createBoardGame().play();
}
Most of the concrete implementation of the pattern is placeholder print() statements. The code so far establishes a series of games between two players, creates a board game via the factory method from which the pattern gets its name, then plays the game. Currently, this results in output along the lines of:
$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
  CheckersGame
    Player One starts with: 12 pieces
    Player Two starts with: 12 pieces
    --
    Winner: Player One

  ThermoNuclearWar
    Player One starts with: 1,000 warheads
    Player Two starts with: 1,000 warheads
    --
    Winner: None

  ChessGame
    Player One starts with: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    Player Two starts with: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    --
    Winner: Player One
That seems a decent example of the pattern except that the placeholder code is starting out with ugliness. Specifically, the products in the patterns—the various board games—are on the repetitive side:
class ChessGame extends BoardGame {
  List playerOnePieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
  List playerTwoPieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
}
What the various BoardGame classes need is a common way to create the initial set of pieces on the board. If only there were a design pattern that could help with that…

Say, that sounds like a factory method pattern! Now, I know what you're thinking, a factory inside a factory—that's typical pattern fanboyism. I'm not going to argue with you, but I beg your patience for just a bit...

If BoardGame is now a factory, I need it to declare a factory method for its subclasses to implement. Since it needs to generate game pieces for the start of a game, I have it require a _createPieces() method:
abstract class BoardGame {
  GamePieces playerOnePieces, playerTwoPieces;
  BoardGame() {
    playerOnePieces = _createPieces();
    playerTwoPieces = _createPieces();
  }
  GamePieces _createPieces();
  // ...
}
Both player one and player two will be assigned the same number of pieces to begin, so the constructor assigns both player one's and player two's pieces to the results of the _createPieces factory method. But the abstract BoardGame does not know how to create chess, checkers, etc. pieces. Subclasses need to define these:
class ChessGame extends BoardGame {
  GamePieces _createPieces() => new ChessPieces();
}

class CheckersGame extends BoardGame {
  GamePieces _createPieces() => new CheckersPieces();
}

class ThermoNuclearWar extends BoardGame {
  GamePieces _createPieces() => new ThermoNuclearPieces();
  String get winner => "None";
}
With that, my board game classes are significantly DRYer and better able to define the functionality behind the actual game play.

But back to the factory-in-a-factory craziness that I have inflicted on myself. I think it actually makes sense. From an illustrative standpoint, it is over the top, but it feels like a reasonable, organic structure. Perhaps last night's GameFactoryGameBoard creator/product was somewhat artificial, but I need to generate different gameboards at runtime, so that makes a decent amount of sense. If anything, tonight's approach feels even better. Each boardgame needs to layout and assign pieces to the players, so a factory method serves nicely in that capacity.

In fact, it makes so much sense that it is a flavor of the factory method pattern: the parallel class hierarchy variation. By taking this approach, I know that, for each type of board game in the BoardGame class hierarchy, there will be a corresponding entry in the hierarchy of the GamePieces classes. The ChessGame needs to use ChessPieces in order to populate the game:
class ChessGame extends BoardGame {
  GamePieces _createPieces() => new ChessPieces();
}
Armed with that knowledge, the client code can make use of this as well. For example it could restart a game or start a new one:
  series.start();
  var game;
  game = series.createBoardGame('Checkers');
  game.play();
  // Start over
  game.playerOnePieces = game._createPieces();
  game.playerTwoPieces = game._createPieces();
  game.play();
That might be a little more useful in another example (a restart() method would make most sense in this example), but it still serves to illustrate some of the potential of this parallel hierarchy approach. I may examine a different example tomorrow to get a better handle on this. Or I may switch to mirrors. Either way, it is sure to be more fun with factories!

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


Day #87

Friday, February 5, 2016

Factory Method without Factory Subclasses


I am already bored by the factory method pattern. Time for Dart mirrors! I kid of course. About the bored, not the mirrors. I goes without saying that I'm going to add mirrors.

The Gang of Four book mentions two major varieties of the pattern: one that uses an abstract class, forcing subclasses to define the factory implementations, and the other in which the creator class provides a default factory implementation. I tried the the former last night, so tonight I try with a default implementation.

For this example, I adopt the Delphi example on the Wikipedia page, which describes a game factory. For this example, two players want to play a series of games against each other. The creator for that might look like:
// Creator
class GameFactory {
  String playerOne, playerTwo;
  GameFactory(this.playerOne, this.playerTwo);
  String toString() => "*** $playerOne vs. $playerTwo ***";

  // The factory method
  BoardGame createBoardGame([String game]) {
    if (game == 'Checkers') return new CheckersGame();
    if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
    return new ChessGame();
  }
}
The constructor requires the names of both players. Once they are ready to play a game, they might choose a game from a text based listing of games, passing the name to createBoardGame(). In this example, there are no subclasses for the creator—the GameFactory knows how to create all products.

The "products" in this version of the pattern are different board games that can be played in the system. Each will need a list of pieces that can be played:
// Product
class BoardGame {
  List playerOnePieces = [];
  List playerTwoPieces = [];

  String get winner => new Random().nextBool() ? 
    "Player One" : "Player Two";
  String toString() =>
    "  ${this.runtimeType}\n"
    "    Player One has: ${playerOnePieces.join(', ')}\n"
    "    Player Two has: ${playerTwoPieces.join(', ')}\n"
    "    Winner: $winner\n";
}
So a chess game would look like:
class ChessGame extends BoardGame {
  List playerOnePieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
  List playerTwoPieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
}
There is some redundancy there, but I will worry about that another time. For now, I have my single creator class and various product classes. Which means that I am ready for some client code.

I start with the creator, which starts the game series between two players:
  var series = new GameFactory('Professor Falken', 'Joshua');
  print(series);
Then they can play various games, choosing each from the text listing on the main menu:
  game = series.createBoardGame('Checkers');
  print(game);

  game = series.createBoardGame('Thermo Nuclear War');
  print(game);

  game = series.createBoardGame();
  print(game);
Running this would result in something like the following output:
$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
  CheckersGame
    Player One has: 12 pieces
    Player Two has: 12 pieces
    Winner: Player Two

  ThermoNuclearWar
    Player One has: 1,000 warheads
    Player Two has: 1,000 warheads
    Winner: None

  ChessGame
    Player One has: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    Player Two has: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    Winner: Player One
So there you go: a factory method pattern example in which the creator is a concrete class, provided a default product, and can supply all products. It does not feel terribly different from last night's example. In fact, it feels almost too simple to warrant the creator class. Except for the need to remember the two players' names, this could almost be done in client code.

I am unsure if this is the example that I would like to use in Design Patterns in Dart as it is a tad simplistic. Then again, there are some opportunities for improving the code that may make it more illustrative. That's something for tomorrow. Plus mirrors!

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


Day #86