Showing posts with label factory method pattern. Show all posts
Showing posts with label factory method pattern. Show all posts

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 GameFactory → GameBoard 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

Thursday, February 4, 2016

Factory Method Pattern (Take 2)


Crazy what happens when you start writing a book, take a break for a year and a half, then come back. I had completely forgotten that I have already researched the factory method pattern for Design Patterns in Dart. But research it I did.

Crazy too is that the approach I was taking to design patterns back then is very different to the one that I have been doing on this recent chain of posts. My focus recently has been to understand the consequences of patterns and different approaches to the pattern. Back then I spent the entire time benchmarking. I think it is especially funny that I included benchmarks for a mirror based solution—some things don't change.

To gain a better understanding of the pattern, I start anew. For my initial example, I adapt the Java example maze from the Wikipedia page which itself was adapted from the C++ example in the Gang of Four book.

The prime mover in this pattern is the "creator" class. In the maze example, the MazeGame is the creator:
abstract class MazeGame {
  List<Room> rooms = [];

  MazeGame() {
    Room room1 = _makeRoom();
    Room room2 = _makeRoom();
    room1.connect(room2);
    addRoom(room1);
    addRoom(room2);
  }

  Room _makeRoom();

  void addRoom(Room r) { rooms.add(r); }
}
The constructor for this class creates 2 rooms, connects them, and adds the 2 rooms to the game. The _makeRoom() method is left abstract by virtue of having no method body. In other words, it is up to concrete implementations of this class to define how to make a room. This is the crux of the pattern. The MazeGame does not know the exact type of rooms with which it will be working, so it delegates that responsibility to subclasses.

The first concrete creator might create nothing but magic rooms in a magic maze:
class MagicMazeGame extends MazeGame {
  @override
  Room _makeRoom() => new MagicRoom();
}
A second concrete creator might create nothing but ordinary rooms for an early level in the game:
class OrdinaryMazeGame extends MazeGame {
  @override
  Room _makeRoom() => new OrdinaryRoom();
}
More interestingly, there is nothing stopping me from generating any kind of room in a subclass:
class CrazyMazeGame extends MazeGame {
  @override
  Room _makeRoom() =>
    new Random().nextBool() ? new OrdinaryRoom() : new MagicRoom();
}
That is the pattern in a nutshell. The things being created are "products" in this pattern. Products in this pattern have no requirements other than there must be multiple types—otherwise there is no reason for a subclass to choose. The Room product that will work with that above code might look like:
// Product
class Room {
  List connectedRooms = [];

  void connect(Room other) {
    connectedRooms.add(other);
  }
}

// Concrete Product #1
class MagicRoom extends Room {}

// Concrete Product #1
class OrdinaryRoom extends Room {}
With that, client code can make use of the creator class:
  MazeGame crazyGame = new CrazyMazeGame();
  print(crazyGame);
Which results in something like:
$ ./bin/maze.dart
CrazyMazeGame has 2 rooms: Instance of 'MagicRoom', Instance of 'OrdinaryRoom'
That will do for an introduction to the pattern. There are still implications to explore. I would also like to come up with a "modern web" example of the pattern. Way back when, I used this pattern in a Backbone.js knockoff, so I might do that again. It would be better, however, to come up with something a little more accessible to most programmers. Grist for forthcoming days.

Play with the code so far on DartPad: https://dartpad.dartlang.org/561d021f19910a79c194.


Day #85

Thursday, July 24, 2014

Logarithmic Scales: For When the Winner is That Big


Up tonight: whatever breaks when I try my all-encompassing, Design Patterns in Dart benchmarking suite on a different pattern. I have been building it out on code for the Visitor Pattern and I think it is finally ready (more or less). So let's see what happens when I pull it back into the code for the Factory Method Pattern.

Note: the code is located at https://github.com/eee-c/design-patterns-in-dart. The current HEAD points to bec37fd41e.

What I found in the Visitor Pattern code was that the benchmark numbers were dependent on the number of times that a particular pattern was run through a loop. This could be specific to patterns that work on node structures like then Visitor Pattern. But for all I know, different approaches like storing a list of Factories in a Map might also be influenced by the number of times through a loop. There is only one way to find out…

I start with a little code re-organization. I think I have settled on storing the preferred solution directly in the lib directory of the particular pattern being explored while alternatives go in lib/alt. After that, I create a separate benchmark script for each approach in the tool directory:
$ tree tool
tool
├── benchmark.sh
├── benchmark.dart
├── benchmark_map_of_factories.dart
├── benchmark_mirrors.dart
└── packages -> ../packages
I also create a mostly-configuration benchmark.sh Bash script file that pulls in common code to run each of those Dart scripts. And it all works pretty brilliantly. Except for the 2 errors per script that cause each benchmark to crash:
Unhandled exception:
FileSystemException: Cannot open file, path = '/home/chris/repos/design-patterns-in-dart/factory_method/tool/packages/args/args.dart' (OS Error: No s)
#0      _rootHandleUncaughtError.<anonymous closure>. (dart:async/zone.dart:713)
...
The solution is fairly simple, though it does expose yet another gap in my thinking—this time regarding Dart Pub packages. Before moving the benchmarking code into a common package location, it was a development dependency for the Visitor Pattern code:
name: visitor_code
dev_dependencies:
  args: any
  benchmark_harness: any
That is no longer needed directly by the pattern code—the common benchmarking code parses command-line arguments now. Only it is clearly not being pulled into this factory method “application.” The factory method application depends on the common dpid_benchmarking package:
name: factory_method_code
dependencies:
  browser: any
dev_dependencies:
  dpid_benchmarking:
    path: ../packages/benchmarking
And dpid_benchmarking does depend on args:
name: dpid_benchmarking
dev_dependencies:
  args: any
  benchmark_harness: any
So why doesn't args get pulled into the application as well?

The answer is simple, really. It is a development dependency of dpid_benchmarking. In other words, it will get installed when used by other applications or packages (like my factory method code). As a development dependency, it is only installed when working directly with the package—when developing it in isolation.

This is not completely obvious. I had not given this much thought, but I realize now that I expected this package's development dependencies to be installed by my application's development dependencies. Somewhere in the back of my mind I was expecting the development dependency on dpid_benchmarking to pull in dpid_benchmarking's development dependencies as well.

Now that I have exposed this flawed thinking, I acknowledge that it was erroneous. Development dependencies are for single package development only. Hopefully I will remember that.

That issue aside, everything else just works. I get nice graphs that seem to prove that the number of times that a Factory Method implementation is used has no impact on its performance:



It may be a little hard to see, but there is a number associated with the “classic” subclass implementation of the Factory Method pattern—it is just really small compared to the other two approaches. For this, I tell gnuplot to plot the y axis logarithmically:
set style data histogram
set style histogram clustered
set style fill solid border
set xtics rotate out
set key tmargin
set xlabel "Loop Size"
set ylabel "µs per run"

set logscale y

plot for [COL=2:4] filename using COL:xticlabels(1) title columnheader
That gives me:



Any way that you look at it, the class subclass approach is the clear performance winner. There may be some maintainability wins for the other approaches, but they would have to be significant to warrant using them over the subclass approach. Even when compiled to JavaScript:



I think that will close out my initial research into object oriented design patterns for the book. I may investigate some concurrency patterns tomorrow. Or it may be time to switch back to Patterns in Polymer.


Day #132

Tuesday, July 22, 2014

Internal Dart Packages for Organizing Codebases


This may very well apply only to me…

I would like to re-use some shell and Dart benchmarking code. I will not be duplicating code so I have to find a working solution. The problem with which I am faced is that I am not working on a single Dart package, but dozens—one for each pattern that will be covered in Design Patterns in Dart. Each package has its own internal Dart Pub structure, complete with pubspec.yaml and the usual subdirectories:
$ tree -L 2
.
├── factory_method
│   ├── build
│   ├── lib
│   ├── packages
│   ├── pubspec.lock
│   ├── pubspec.yaml
│   ├── tool
│   └── web
└── visitor
    ├── bin
    ├── lib
    ├── packages
    ├── pubspec.lock
    ├── pubspec.yaml
    └── tool
The code that I would like to share currently exists only in the Visitor Pattern's tool subdirectory. I suppose that I could create another top-level directory like helpers and then import the common code into visitor, factory_method and the still-to-be-written directories. That seems like a recipe for an unmaintainable codebase—I will wind up with crazy depths and amounts of relative imports (e.g. import '../../../../helpers/benchmark.dart') strewn about. And the coding gods help me should I ever want to rename things.

Instead, I think that I will create a top-level packages directory to hold my common benchmarking code, as well as any other common code that I might want to use. As the name suggests, I can create this as an actual Dart Pub package, but instead of publishing it to pub.dartlang.org, I can keep it local:
$ tree -L 2
.
├── factory_method
│   └── ...
├── packages
│   └── benchmarking
└── visitor
    └── ...
I am probably going to regret this, but I named the package's subdirectory as the relatively brief ”benchmarking,” but name the package dpid_benchmarking in pubspec.yaml. The idea here is to save a few keystrokes on the directory name, but ensure that my local package names do not conflict with any that might need to be used as dependencies. So in packages/benchmarking, I create a pubspec.yaml for my local-only package:
name: dpid_benchmarking
dev_dependencies:
  args: any
  benchmark_harness: any
There is nothing fancy there—it reads like any other package specification in Dart, which is nice.

The first bit of common code that I would like to pull in is not Dart. Rather it is the common _benchmark.sh Bash code from last night. There is nothing in Dart's packages that prevent packaging other languages, a fact that I exploit here:
$ git mv visitor/tool/_benchmark.sh packages/benchmarking/lib
I use the lib subdirectory in the package because that is the only location that is readily shared by Dart packages.

To use _benchmark.sh from the vistor code samples, I now need to declare that it depends on my local-only package. This can be done in pubspec.yaml with a dependency. Since this is benchmarking code, it is not a build dependency. Rather it is a development dependency. And, since this is a local-only package, I have to specify a path attribute for my development dependency:
name: visitor_code
dev_dependencies:
  dpid_benchmarking:
    path: ../packages/benchmarking
I suffer a single relative path in my pubspec.yaml because Pub rewards me with a common, non-relative path after pub install. Installing this local-only package creates a symbolic link to packages/dpid_benchmarking/lib in the packages directory:
$ pwd
/home/chris/repos/design-patterns-in-dart/visitor
$ ls -l packages 
lrwxrwxrwx 1 chris chris 31 Jul 22 21:35 dpid_benchmarking -> ../../packages/benchmarking/lib
lrwxrwxrwx 1 chris chris  6 Jul 22 21:35 visitor_code -> ../lib
Especially useful here is that Dart Pub creates this packages directory in all of the standard pub subdirectories like tool:
$ cd tool
$ pwd
/home/chris/repos/design-patterns-in-dart/visitor/tool
$ ls -l packages/
lrwxrwxrwx 1 chris chris 31 Jul 22 21:35 dpid_benchmarking -> ../../packages/benchmarking/lib
lrwxrwxrwx 1 chris chris  6 Jul 22 21:35 visitor_code -> ../lib
This is wonderfully useful in my visitor pattern's benchmark.sh Bash script. Instead of sourcing _benchmark.sh in the current tool directory, I simply change it so that it sources it from the local-only package:
#!/bin/bash

source ./packages/dpid_benchmarking/_benchmark.sh

BENCHMARK_SCRIPTS=(
    tool/benchmark.dart
    tool/benchmark_single_dispatch_iteration.dart
    tool/benchmark_visitor_traverse.dart
)

_run_benchmarks $1
The symbolic links from Dart Pub takes care of the rest. Nice!

Of course, Pub is the Dart package manager, so it works with Dart code as well. I move some obvious candidates for common benchmarking from visitor/tool/src into the local-only package:
$ git mv visitor/tool/src/config.dart packages/benchmarking/lib/
$ git mv visitor/tool/src/score_emitters.dart packages/benchmarking/lib/
It is then a simple matter of changing the import statements to use the local-only package:
import 'package:dpid_benchmarking/config.dart';
import 'package:dpid_benchmarking/score_emitters.dart';
import 'package:visitor_code/visitor.dart';

main (List args) {
  // ...
}
Dart takes care of the rest!

Best of all, I rinse and repeat in the rest of my design patterns. I add the dpid_benchmarking local-only package as a development dependency, run pub install, then make use of this common code to ensure that I have beautiful data to back up some beautiful design patterns.

That is an all-around win thanks to Dart's Pub package manager. Yay!


Day #130

Monday, June 30, 2014

Benchmarking Dart (and dart2js) Code in the Browser


I am a benchmarking fool. I so enjoyed benchmarking various implementations of the Factory Method pattern, that I try it again today. Yesterday I ran the benchmarks from the command-line. Today, I wonder what my options are for benchmarking Dart code in the browser.

To benchmark Dart from the command-line, I used the dart system command that comes with the SDK. For good measure, I also compiled my benchmark harness into JavaScript and ran it with node.js. Amazingly, that worked without any effort on my part.

It worked so well, I thought why not try it in the browser? There may wind up being a web-specific design pattern or two in Design Patterns in Dart, so while this benchmarking stuff is fresh in my brain, I ought to see how it might work in the browser instead of from the command-line. With a qualifier...

Even though these benchmarks will be run in the browser, I want the results readily accessible from the command-line. I would like the ability to review progress of any benchmarks as I refine pattern approaches and that needs to be automated or it simply won't happen.

So I create a web sub-directory in my factory_method sample code, copy in yesterday's benchmark.dart and start with a simple index.html:
<!DOCTYPE html>
<html>
  <head>
    <script type="application/dart" src="benchmark.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </head>
  <body></body>
</html>
I do not know how these things are normally done in JavaScript, but if I want the console.log output from Dart code, I stick with content_shell, which is bundled with the SDK. And this works right off the bat:
$ content_shell --dump-render-tree web/index.html
#READY
CONSOLE MESSAGE: Factory Method — Subclass(RunTime): 0.09106837778077291 us.
CONSOLE MESSAGE: Factory Method — Map of Factories(RunTime): 1.8514472763359118 us.
CONSOLE MESSAGE: Factory Method — Mirrors(RunTime): 12.328632014991616 us.
Content-Type: text/plain
layer at (0,0) size 800x600
  RenderView at (0,0) size 800x600
layer at (0,0) size 800x8
  RenderBlock {HTML} at (0,0) size 800x8
    RenderBody {BODY} at (8,8) size 784x0
#EOF
#EOF
#EOF
Nice. Those numbers are comparable to the Dart command-line numbers from yesterday, so all appears to be in good shape with benchmarking pure Dart in the browser. What about dart2js compiled JavaScript?

I could try dumping it into a test runner like Karma, but that seems crazy. I mean more crazy than most of the stuff I try. Maybe content_shell will work for this as well? To test that out, I pub build my benchmark application which compiles the index.html page and associated code:
$ pub build
Loading source assets...
Building factory_method_code...
[Info from Dart2JS]:
Compiling factory_method_code|web/benchmark.dart...
[Dart2JS on factory_method_code|web/benchmark.dart]:
1 warning(s) suppressed in dart:_js_mirrors.
[Warning from Dart2JS]:
web/benchmark.dart:
2391 methods retained for use by dart:mirrors out of 3411 total methods (70%).
[Info from Dart2JS on factory_method_code|web/benchmark.dart]:
packages/factory_method_code/mirrors.dart:3:1:
This import is not annotated with @MirrorsUsed, which may lead to unnecessarily large generated code.
Try adding '@MirrorsUsed(...)' as described at https://goo.gl/Akrrog.
import 'dart:mirrors';
^^^^^^^^^^^^^^^^^^^^^^
[Info from Dart2JS]:
Took 0:00:13.648601 to compile factory_method_code|web/benchmark.dart.
Built 5 files to "build".
Note to self: I really need to look into that @MirrorUsed annotation. Some other day.

For now, I have compiled JavaScript and page in the build directory:
$ tree -L 2 build
build
└── web
    ├── benchmark.dart.js
    ├── benchmark.dart.precompiled.js
    ├── index.html
    └── packages

2 directories, 3 files
I cannot just run that code because content_shell from the Dart SDK has the Dart VM included. With the Dart VM available, content_shell would try to run the Dart code which was not included in the build process.

So, just to see if this works, I hand-edit the generated HTML to directly point to the compiled benchmark.dart.js file instead of relying on the usual browser/dart.js to do it:
<!DOCTYPE html>
<html>
  <head>
    <!-- <script type="application/dart" src="benchmark.dart"></script> -->
    <!-- <script src="packages/browser/dart.js"></script> -->
    <script src="benchmark.dart.js"></script>
  </head>
  <body></body>
</html>
With that, I can run content_shell against build/web/index.html to find:
content_shell --dump-render-tree build/web/index.html
CONSOLE MESSAGE: line 14349: Factory Method — Subclass(RunTime): 0.46883995866706923 us.
CONSOLE MESSAGE: line 14349: Factory Method — Map of Factories(RunTime): 5.1614768017425146 us.
CONSOLE MESSAGE: line 14349: Factory Method — Mirrors(RunTime): 16.81279790176282 us.
Content-Type: text/plain
layer at (0,0) size 800x600
  RenderView at (0,0) size 800x600
layer at (0,0) size 800x8
  RenderBlock {HTML} at (0,0) size 800x8
    RenderBody {BODY} at (8,8) size 784x0
#EOF
#EOF
#EOF
Again, those numbers are comparable to the command-line dart2js results from yesterday which seems to confirm that this will work.

Unless someone cares an awful lot (and tells me that I am mistaken), this seems a reasonable approach to benchmarking in the browser. I may poke around a little more tomorrow—or jump right into adding a pub build transformer to automatically change the <script> tags that I hand edited today.

But so far, this seems promising.


Day #108

Sunday, June 29, 2014

Benchmarking dart2js Code


I probably have enough initial research on the Factory Method to get me started with Design Patterns in Dart. I do not necessarily need to have all the questions answered at this point, but I hope to have done enough to begin to understand what questions to ask.

But before I move on from this creational design pattern to a (likely) behavioral pattern, I would like to try one more benchmark. Specifically, I would like to see how my mirror-based pattern fares in the benchmark_harness sweepstakes.

The classic Factory Method pattern done in Dart looks something like:
abstract class Creator {
  Product productMaker();
}

abstract class Product {}

class ConcreteCreator extends Creator {
  productMaker()=> new ConcreteProduct();
}

class ConcreteProduct extends Product {}
The intent here is to defer the specific instance of the product to be created to a subclass. Here, the Creator does not know which subclass of Product that a subclass would want, so it declares productMaker() as an abstract method (in Dart, that means no method body). A subclass of the creator—here ConcreteCreator—then defines producMaker() to return something useful.

For me, it is helpful to think of the creator class as the base collection class in a web MVC framework. In such a case, the framework collection has no way of know what kinds of models it will be holding, so it defers the creation of those objects to the subclass in actual application code.

In contrast to this subclass approach, the mirror approach does not rely on the concrete creator to generate concrete products. Instead, it merely defines the class that will be used. The creator base class can use that to generate instances of the concrete product—thanks to the magic of mirrors:
import 'dart:mirrors';

abstract class Creator {
  Type productClass;

  Product productMaker() {
    return reflectClass(productClass).
      newInstance(const Symbol(''), []).
      reflectee;
  }
}

abstract class Product {}

class ConcreteCreator extends Creator {
  Type productClass = ConcreteProduct;
}

class ConcreteProduct extends Product {}
Regardless of your feelings on the syntax of mirrors in the Creator base class, the remainder of the code in the pattern is mercifully terse. But how fast is it?

Using the same approach to benchmarking that I have for the subclass approach (and last night's map-of-factories), my benchmark harness for my mirror approach looks like:
import 'package:benchmark_harness/benchmark_harness.dart';
import 'package:factory_method_code/mirrors.dart' as Mirrors;
// ...
class FactoryMethodMirrorBenchmark extends BenchmarkBase {
  const FactoryMethodMirrorBenchmark() : super("Factory Method — Mirrors");
  static void main() { new FactoryMethodMirrorBenchmark().report(); }
  void run() {
    new Mirrors.ConcreteCreator().productMaker();
  }
}
As in the other Factory method approaches, I am measuring the time that it takes to create an instance of the concrete creator and invoke the productMaker(). I add this benchmark to the main() entry point in my code as:
import 'package:benchmark_harness/benchmark_harness.dart';
// ...
main() {
  FactoryMethodSubclassBenchmark.main();
  FactoryMethodMapBenchmark.main();
  FactoryMethodMirrorBenchmark.main();
}
With that, I find:
$ dart tool/benchmark.dart                
Factory Method — Subclass(RunTime): 0.08687553108098094 us.
Factory Method — Map of Factories(RunTime): 1.7346083861377035 us.
Factory Method — Mirrors(RunTime): 12.741612833352447 us.
Well, that was pretty much to be expected. The map-of-factories approach is 20 times slower than the traditional subclass approach and the mirror approach is 7 times slower than the map of factories. This does not rule out the slower two approaches as they can still be useful in certain situations—especially when it is unlikely that many concrete products will be instantiated. Still, it darned handy to be able to understand the tradeoffs when making these decisions.

Except...

Do I really understand the tradeoffs as the code is likely to be run? Since the primary usage of Dart code is compiled to JavaScript. I really ought to understand what the numbers are like when compiled. But how?

As a first pass, I simply compile to JavaScript:
$ dart2js -o factory_method/tool/benchmark.dart.js factory_method/tool/benchmark.dart
Hint: 1 warning(s) suppressed in dart:_js_mirrors.
factory_method/tool/benchmark.dart:
Hint: 2391 methods retained for use by dart:mirrors out of 3411 total methods (70%).

factory_method/tool/packages/factory_method_code/mirrors.dart:3:1:
Info: This import is not annotated with @MirrorsUsed, which may lead to unnecessarily large generated code.
Try adding '@MirrorsUsed(...)' as described at https://goo.gl/Akrrog.
import 'dart:mirrors';
^^^^^^^^^^^^^^^^^^^^^^
Then I run the JavaScript with Node.js:
$ node factory_method/tool/benchmark.dart.js
Factory Method — Subclass(RunTime): 0.11682296216069209 us.
Factory Method — Map of Factories(RunTime): 4.732708458059921 us.
Factory Method — Mirrors(RunTime): 8.318221896887321 us.
Whoa. That actually worked.

Also: tnteresting. The mirror version (even though it is likely huge) is noticeably faster than its Dart counterpart whereas the other two approaches are significantly slower than their counterparts.

That aside, the map-of-factories approach is 40 times slower than the subclass approach, which is around the same order of magnitude as the Dart difference. The mirror approach is only twice as slow as the map-of-factories approach. That is still worth noting, but if you are a fan of the resulting code, then perhaps mirrors should not be immediately overlooked.

I also note that I am surprised that Node was able to run the dart2js output without any problem. Perhaps it should not surprise me, but I expected at least one or two problems. This was a pleasant surprise.


Day #107

Saturday, June 28, 2014

Benchmarking Apples and Apples


I left off yesterday with some initial benchmarks for Design Patterns in Dart. The benchmark_harness makes that pretty darn easy. What I found was that one of my Factory Method pattern implementation was not the same as the other.

Speed is not the only concern when picking an implementation, but it is certainly good to know. For the Factory Method, the fastest that I found was the classic subclass approach:
abstract class Creator {
  Product productMaker();
}

abstract class Product {}

class ConcreteCreator extends Creator {
  productMaker()=> new ConcreteProduct();
}

class ConcreteProduct extends Product {}
The abstract creator describes that subclasses will be responsible for choosing the class to instantiate. In this case it is a new ConcreteProduct, mirroring the role in the pattern. When I use the pattern in Dart Comics, the collection chooses to create a concrete ComicBook. The point being that the subclass can choose whatever it likes. And it is fast.

The alternate approach uses a Map of factories, enabling the top-level creator to sport a default implementation:
typedef Product productFactory();
Map<Type, productFactory> Factory = {
  ConcreteCreator: (){ return new ConcreteProduct(); }
};

abstract class Creator {
  Product productMaker()=> Factory[this.runtimeType]();
}

abstract class Product {}

class ConcreteCreator extends Creator {}
class ConcreteProduct extends Product {}
Yesterday, I found that subclass approach was roughly 600% faster than the map-of-factories implementation. It is actually even better than that. After updating to Dart 1.5, the results are now:
$ dart tool/benchmark.dart
Factory Method — Subclass(RunTime): 0.08871921437716161 us.
Factory Method — Map of Factories(RunTime): 1.7642425092468361 us.
1800% faster. That's craziness. But...

It is not quite a fair comparison. The productMaker() from the subclass version immediately creates the concrete instance. Calling the productMaker() method in the map-of-factories version does not immediately instantiate the concrete instance. Instead, it calls a closure that creates and returns the object. Perhaps this indirection makes a difference?

To find out, I replace the productMaker() method in the map-of-factories approach with a getter that returns the factory method:
typedef Product productFactory();
Map<Type, productFactory> Factory = {
  ConcreteCreator: (){ return new ConcreteProduct(); }
};

abstract class Creator {
  productFactory get productMaker=> Factory[this.runtimeType];
}
// ...
The dynamic language dork in me loves this kind of thing, but it is probably a little hard to read. The productMaker getter returns the Map lookup in Factory. The value returned from the Factory lookup, and hence from the productMaker getter, is a closure—an anonymous function. This return value can be invoked with the call operator—open and closing parenthesis. So it looks just like a method call:
new MapOfFactories.ConcreteCreator().productMaker();
But it is not a method—I am immediately invoking the result of the Map lookup.

Cool, eh? Well, I like it. Anyway, the result of all that? No change whatsoever:
$ dart tool/benchmark.dart
Factory Method — Subclass(RunTime): 0.08664997297170718 us.
Factory Method — Map of Factories(RunTime): 1.7268800975341878 us.
Well, maybe a slight improvement, but it is unclear if the improvement is statistically significant.

So, unless I am missing some obvious way to improve things, my map-of-factories approach is 20 times slower than the subclass approach. There are times in which this will not matter (e.g. when I am not creating a large quantity of concrete products), but this certainly needs to factor into choosing an implementation.


Day #106

Friday, June 27, 2014

Benchmarking Factory Method Pattern Approaches in Dart


A week of background work on Design Patterns in Dart has left me with more questions than answers. I expected as much.

The big questions that I have only started to grasp mostly revolve around organizing code that will support the book—especially “code in the wild.” Since most code will be available on GitHub, I will likely at least have an account there, but I might need an Organization with multiple accounts to keep everything organized. As private repos and submodules dance in my head, I try to keep my sights on something a little more concrete—benchmarks.

At least some the reasoning behind certain design patterns and approaches to design patterns will be born of performance concerns, so I need to start thinking about how to approach this. Do I keep the harness in a public repository? Do I have a public facing book repository with the harness that includes the private book repository as a submodule? Submodules? Really?

Gah! I'm terrible at maintaining focus on the small stuff. BUT, for tonight I am just going to set up a test harness in the Factory Method code that I have devised so far to see how it runs.

I have mostly been working with existing codebases so far, but for benchmarking, it is best to use small, sample code lest additional complexity impact the numbers. So I start a new factory_method Dart Pub package, starting with the pubspec.yaml package file:
name: factory_method_code
dev_dependencies:
  benchmark_harness: any
For benchmarking in Dart, the benchmark_harness is probably all that anyone will ever need. Before installing it from pubspec.yaml, I lay out the rest of the code. I start with lib/subclass.dart which contains a subclass example of the Factory method:
library factory_method_subclass;

abstract class Creator {
  Product productMaker();
}

abstract class Product {}

class ConcreteCreator extends Creator {
  productMaker()=> new ConcreteProduct();
}

class ConcreteProduct extends Product {}
Next, I create the benchmark “tool” in tool/benchmark.dart:
import 'package:benchmark_harness/benchmark_harness.dart';
import 'package:factory_method_code/subclass.dart';

class FactoryMethodSubclassBenchmark extends BenchmarkBase {
  const FactoryMethodSubclassBenchmark() : super("Factory Method — Subclass");

  static void main() {
    new FactoryMethodSubclassBenchmark().report();
  }

  // The benchmark code.
  void run() {
    new ConcreteCreator().productMaker();
  }
}

main() {
  // Run FactoryMethodSubclassBenchmark
  FactoryMethodSubclassBenchmark.main();
}
Most of that is copied directly from the Example provided on the benchmark_harness page.

With the code and directory structure in place, I now install the pubspec.yaml dependencies with pub install:
➜  factory_method git:(master) ✗ pub install
Resolving dependencies... (1.4s)
Downloading benchmark_harness 1.0.4...
Got dependencies!
With that, I can run my benchmark:
➜  factory_method git:(master) ✗ dart tool/benchmark.dart
Factory Method — Subclass(RunTime): 0.24725152118407764 us.
OK that is definitely a number, but without something to compare it to, it is a pretty useless number. I might as well compare it to the map-of-factories approach to Factory Method from last night. I think this can be boiled down to:
typedef Product productMaker();
Map<Type, productMaker> Factory = {
  ConcreteCreator: (){ return new ConcreteProduct(); }
};

abstract class Creator {
  Product productMaker()=> Factory[this.runtimeType]();
}

abstract class Product {}

class ConcreteCreator extends Creator {}

class ConcreteProduct extends Product {}
When it comes to the benchmarking code, I hit my first snag. The creator and product classes are names the same in both samples. If I import both into my benchmark file, I will get class conflicts. So I need to prefix the imports:
import 'package:benchmark_harness/benchmark_harness.dart';
import 'package:factory_method_code/subclass.dart' as Subclass;
import 'package:factory_method_code/map_of_factories.dart' as MapOfFactories;

class FactoryMethodSubclassBenchmark extends BenchmarkBase {
  // ...
  void run() {
    new Subclass.ConcreteCreator().productMaker();
  }
}

class FactoryMethodMapBenchmark extends BenchmarkBase {
  const FactoryMethodMapBenchmark() : super("Factory Method — Map of Factories");

  static void main() {
    new FactoryMethodMapBenchmark().report();
  }

  void run() {
    new MapOfFactories.ConcreteCreator().productMaker();
  }
}

main() {
  FactoryMethodSubclassBenchmark.main();
  FactoryMethodMapBenchmark.main();
}
Aside from that, everything else works perfectly. And when I run my double benchmarks, I get:
➜  factory_method git:(master) ✗ dart tool/benchmark.dart
Factory Method — Subclass(RunTime): 0.24548983015417866 us.
Factory Method — Map of Factories(RunTime): 1.900878681170371 us.
Yikes! The map of factories approach is more than 600% slower. I expected the subclass approach to be quicker, but that amount really surprises me. So much so that I wonder if I am testing both at similar levels of abstraction. I will ruminate on this tomorrow (and also pull in tests of my mirror approach).

Regardless, this benchmarking approach seems reasonable. It is good to be aware of the need to prefix the imports, but that aside, this seems a good way to obtain admittedly illuminating numbers.


Day #105

Thursday, June 26, 2014

Compile Time Constant Factory Method


Tonight I continue to poke and prod the first design pattern destined for Design Patterns in Dart...

I really like yesterday's map-of-factories approach to the Factory Method pattern in Dart. The approach, first suggested to me by Vadim Tsushko removes the immediate responsibility of Factory Methods from subclasses of the creator class and instead places them in a Map of factories. I think I may have left some room for improvement though...

The classic Factory Method pattern starts with an abstract creator class that includes an abstract creator method:
abstract class Creator {
  Product productMaker();
  // ...
}
The Product is similarly abstract—the concrete subclass of Product is deferred to the concrete subclass of Creator. Leaving the productMaker() method abstract says just that: the subclass needs to define a productMaker() method that returns a subclass of Product:
class ConcreteCreator extends Creator {
  productMaker()=> new ConcreteProduct();
}
Yesterday's variation does away with the creator subclass, which is quite nice if the factory method is the only reason to define a subclass. Instead, the top-level creator class now looks up the factory method in a simple Map:
typedef Product productFactory();
class Creator {
  static Map<Type, productFactory> factory = new Map();
  Product productMaker(type) => factory[type]();
  // ...
}
Here, I typedef a function that takes no arguments and returns some kind of concrete Product (just like the original productMaker() factory method). The static factory map is then a key/value store in which the keys are types and the values are product factories.

Either approach (subclass or map-of-factories) will work as a Factory Method implementation. I have yet to benchmark the two. In the absence of that admittedly useful information, the choice between the two comes down to context or personal preference. In the web MVC framework example that I used yesterday, it probably makes more sense to use the subclass approach as I have to create subclasses anyway and the map-of-factories was a little awkward. If the concrete classes are all part of the same codebase or if a parallel class hierarchy needs factories, then map-of-factories seems the better approach.

I do not want to dwell on those question too much just yet. Instead, I am wondering if including the map-of-factories in the creator class is the right approach. Perhaps this was just the codebase upon which I was experimenting last night, but it felt a little messy having it in the same class.

Instead, I would like an entirely separate Factory class to hold this information. Something along the lines of:
typedef Product productFactory();
class Factory {
  static Map<Type, productFactory> factory = new Map();
}
So I give that a try in my Hipster MVC (abstract creator and product) and Dart Comics (concrete creator and product) codebases. In Hipster MVC, the HipsterCollection class had served as the abstract creator, creating HipsterModel objects from attributes fetched via a RESTful backend. Last night it got the map-of-factories treatment. Tonight, I move that out into a separate Factory class:
typedef HipsterModel modelMaker(Map attrs);

class Factory {
  static Map factory = new Map();
}
This works just fine. HipsterCollection is now capable of creating concrete instances of HipsterModel (e.g. ComicBook from Dart Comics) using this Factory:
class HipsterCollection extends IterableBase {
  // ...
  HipsterModel modelMaker(attrs) => Factory.factory[this.runtimeType](attrs);
  // ...
}
But you know what? Factory.factory looks ugly. It would be much cooler if that were just:
  HipsterModel modelMaker(attrs) => Factory[this.runtimeType](attrs);
Unfortunately operators, like the square bracket lookup operator, cannot be static:
class _Factory {
  static Map<Type, modelMaker> factory = new Map();

  // This won't work!!!
  static operator [](type) => factory[type];
}
I know this does not work because I try it out only to get a nice little exception:
Internal error: 'package:hipster_mvc/hipster_factory.dart': error: line 11 pos 19: operator overloading functions cannot be static
  static operator [](type) => factory[type];
Bah!

All is not lost… as long as I am willing to resort to some compile time constant chicanery. And of course I am more than willing. I rename the Factory class as _Factory and declare a compile time constant of Factory which of type _Factory:
_Factory Factory = const _Factory();

class _Factory {
  static Map<Type, modelMaker> factory = new Map();

  const _Factory();
  operator [](type) => factory[type];
  operator []=(type, function) { factory[type] = function; }
}
Which does the trick, though it feels a little dirty. Dirty because I declare a compile-time constant whose sole purpose is to store changing key-value pairs. But it works because the instance variable factory fails on the _Factory instance which leaves Dart to fall back on static variable lookup.

And it is at this point that I realize that, yes, I am an idiot.

Because I have gone to all of this effort even though an empty HashMap is also a compile time constant. So the _Factory class and Factory compile time constant can be replaced with:
typedef HipsterModel modelMaker(Map attrs);
Map<Type, modelMaker> Factory = {};
Well, that was a long way to go to wind up with a simple HashMap lookup.

Ah well, maybe that const + static method trick will come in handy some day. Stranger things have happened.

But for today, I have my map-of-factories in better shape with an extremely small amount of code. Demonstrating publicly that I'm a dummy is a small price to pay for that!

Tomorrow: benchmarking.



Day #104

Wednesday, June 25, 2014

A Map of Factories for the Factory Method Pattern


Sometimes there is no substitute for doing something stupid—just to see why it is stupid. It is one thing to read that a thing is stupid, but that tactile feeling of failure leaves an imprint that sticks with a person like a quality case of food poisoning. The body may expel the immediate repercussions of food poisoning, but it will be a long time before you try that particular Mediterranean bistro again.

Toward that end I have been doing dumb things with mirrors, named constructors and default implementation approaches to the Factory Method pattern in Dart. Actually not all of those are dumb—it depends on the context in which they are used. And that's going to be a big part of my job in Design Patterns in Dart—figuring out which approaches are decent in the right circumstances and which are the coding equivalent of food poisoning.

Also, I need to come up with really good food poisoning descriptions so that I can fully imprint on the hearty reader which approaches truly are stupid (and why). But that's a skill I can develop later. For now, I try another approach to the Factory Method pattern. This one promises to be rather good...

I continue to work with the Hipster MVC framework. It is a toy MVC framework for the web (built primarily to support Dart for Hipsters). Toy or not, frameworks are fertile ground for raising robust Factory Method patterns. In this case, it has an abstract product, HipsterModel (the “M” in this framework's MVC). It also has an abstract creator, HipsterCollection. The current implementation of the Factory Method in this creator class is the modelMaker():
abstract class HipsterCollection extends IterableBase {
  HipsterModel modelMaker(Map attrs);
  // ...
}
This abstract method is declared so that subclasses will define a method that accepts a Map of attributes and returns a concrete product of type HipsterModel. The concrete creator implementation for a comic book collection (like the one in the Dart Comics application) might look something like:
class Comics extends HipsterCollection {
  modelMaker(attrs) => new ComicBook(attrs);
  String url = '/comics';
}
This is a classic implementation of the Factory Method pattern, done in Dart. It is particularly effective in this framework example. The intent is to maintain a relationship between the creator class (HipsterCollection) and the product class (HipsterModel). Since the framework has no business knowing the concrete class types (ComicBook), using Factory Method defers the concrete instantiation to the concrete creator class.

This approach works pretty darn well for a framework, but there are other approaches to the pattern. An interesting one was suggested by Vadim Tsushko in the comments of a previous post. In Vadim's approach, a subclass of the creator is not responsible for creating concrete products. Instead, that responsibility goes into a Map:
typedef HipsterModel modelMaker(Map attrs);
Map<Type, modelMaker> factory = new Map();
The factory map above is keyed by a Type and returns functions of the modelMaker type. In this approach, modelMaker is typedef'd as a function that accepts a map of attributes and returns an object of type HipsterModel. In other words, modelMaker functions have the exact same signature that my current modelMaker() method has.

To explore this approach in Hipster MVC, I declare the typedef in the collection class and add the factory as a static class variable on the same:
typedef HipsterModel modelMaker(Map attrs);

class HipsterCollection extends IterableBase {
  // ...
  static Map<Type, modelMaker> factory = new Map();

  HipsterModel modelMaker(Map attrs) => factory[this.runtimeType](attrs);
  // ...
}
The modelMaker() method is no longer abstract. Its definition returns the result of invoking the factory for the current runtime type.

The factory for the Comics collection can be added as:
HipsterCollection.factory[Comics] = (attrs) => new Models.ComicBook(attrs);
Once that is registered, an instance of Comics that needs a model (e.g. if it GETs a record via a REST backend) can get one by invoking modelMaker with the attributes. This will lookup the correct factory based on the object's runtimeType, which is Comics. The anonymous function associated with this type will be invoked with the supplied attributes and the result returned.

I rather like that. The implementation is succinct. The resulting code might be a little hard to read, but the associated typedef and Map types clear things up nicely. The result is a subclass of the creator that does no creating itself:
class Comics extends HipsterCollection {
  String url = '/comics';
  // NO LONGER NEEDED :)
  // modelMaker(attrs) => new ComicBook(attrs);
}
The only downside is also a potential benefit, depending on the context. In the case of my framework, I had to assign the HipsterCollection.factory in the main() entry point:
main() {
  HipsterCollection.factory[Comics] = (attrs) => new Models.ComicBook(attrs);
  // ...
}
In certain circumstances this could be a benefit—keeping all of the factory registration in on place. In the case of my framework, this is probably not a good practice. Since I have to subclass the creator class anyway, I might as well put the creator method in that subclass. Even so, I like the factory map approach enough that I will likely include it in the book.


Day #103

Tuesday, June 24, 2014

Default Implementation in Dart Factory Method


Up tonight, I continue my exploration of the Factory Method pattern in Dart. Tonight, I explore a variation in which a default implementation is provided in the base creator class.

Before starting, I note that my current framework sample code may be insufficient for adequately describing the various use-cases of Factory Method. The framework Factory Method comes from the Hipster MVC framework (well, toy framework largely written in support of Dart for Hipsters). The abstract creator in the framework is the collection part of the MVC. It is aptly named HipsterCollection:
abstract class HipsterCollection extends IterableBase {
  // ...
  HipsterModel modelMaker(attrs);
  // ...
}
This abstract creator expects concrete creators to define modelMaker() with appropriate concrete products—in this case the product being a type of HipsterModel, the model in the MVC framework. The sample code that I have been using is a collection of comics books. In this case, ComicBook serves as the concrete product class, extending HipterModel. The concrete creator class, ComicCollection, then subclasses HipsterCollection, defining the modelMaker() factory method as:
class Comics extends HipsterCollection {
  modelMaker(attrs) => new ComicBook(attrs);
  // ...
}
That implementation of the Factory Method pattern works just fine for my framework. The Hispter MVC framework and the application that contains the code defining the abstract portions of the framework are completely separate. One can be a publicly hosted package and the other an application in a private repository. The framework delegates the knowledge of the product class to that private application which is ideal since the publicly available framework should not have any knowledge of application code.

Although this works fine, it does present a slight problem. Programmers using my framework will often wind up with a number of very small creator classes like Comics:
class Comics extends HipsterCollection {
  modelMaker(attrs) => new ComicBook(attrs);
  get url => '/comics';
}
As the Gang of Four book puts it, “Subclassing is fine when the client has to subclass the creator class anyway, but otherwise the client now must deal with another point of evolution.” In my current Comics, I don't really need to subclass HipsterCollection. To be sure, HipsterCollection should expect to be subclassed so that custom events can be set, but in this particular example, I could get away with what the Gang of Four describe as a default implementation.

Unfortunately, here I hit the limitation of my example code. It makes no sense for my public framework to be aware of how to create ComicBook instances. I should explore some of the parameterized examples from the Gang of Four, but I will leave that for another day and another code source. For now, I use a variation in which the client code stores the product class in a static variable, providing a useful default implementation.

In this case, the client code no longer creates an instance of ComicsCollection:
var my_comics_collection = new Collections.Comics();
Instead, it first defines the class to be used when creating models and then creates an instance of HipsterCollection:
HipsterCollection.modelClass = Models.ComicBook;
var my_comics_collection = new HipsterCollection()..url = '/comics';
To support that, HispterCollection can no longer be abstract. Instead it needs to support a reasonable default—using the modelClass static variable:
class HipsterCollection extends IterableBase {
  // ...
  static Type modelClass = HipsterModel;

  HipsterModel modelMaker(attrs) =>
    reflectClass(modelClass).
      newInstance(const Symbol(''), [attrs]).
      reflectee;

  String url;
  // ...
}
Unfortunately, this means the return of Dart mirrors. That might not be a horrible solution in some cases, but I ought to be able to avoid it under most circumstances. This current implementation precludes multiple collection types since HipsterCollection.modelClass can only have one value at a time (I could cache the class in an instance variable, but this already feels awkward).

I think tomorrow it is time to explore the global Map of factory closures proposed in comments from previous nights' posts. Then I need to work up an illustrative example of Factory Method in a single codebase so that some of these other approaches might work—without resorting to mirrors.



Day #102