Thursday, December 31, 2015

Adapting Procedural Code


So the basic adapter pattern in Dart is pretty darn boring. Case closed on research for the forthcoming Dart Design Patterns in Dart? Far from it. I have the utmost confidence in my ability to make things way more complicated than they might at first seem (or need to be).

Toward that end, tonight I try adapting procedural code to an a asynchronous interface. The code that currently powers the design patterns robot is quite procedural:
class Robot {
  // ...
  String get location => "$x, $y";
  void move(direction) {
    print("  I am moving $direction");
    switch (direction) {
      case Direction.NORTH:
        y++;
        break;
      case Direction.SOUTH:
        y--;
        break;
      case Direction.EAST:
        x++;
        break;
      case Direction.WEST:
        x--;
        break;
    }
  }
}
I can easily move my robot forward a far as I like by sending multiple move() messages to the robot:
  var robot = new Robot();
  print("Start moving the robot.");
  robot
    ..move(Direction.NORTH)
    ..move(Direction.NORTH)
    ..move(Direction.NORTH)
    ..move(Direction.NORTH)
    ..move(Direction.NORTH);
  print("The robot is now at: ${robot.location}.");
With that, the robot winds up at 0, 5 (fives paces in the positive Y-direction):
$ ./bin/play_robot.dart
Start moving the robot.
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
The robot is now at: 0, 5.
Unfortunately, this will not work with the Universal Robot Remote Control™. The forward button on the universal remote starts the robot moving forward and does not stop it until some other action occurs (e.g. the button is released, the stop button is pressed, the robot crashes). What I need to do is adapt my robot's one-step-at-a-time interface to the universal remote's continuous motion interface. That means the adapter pattern, yay!

The universal remote might expect a robot interface that looks something like:
library universal_remote;

import 'dart:async';

import 'robot.dart';

abstract class Ubot {
  Timer moveForward();
  Timer moveBackward();
  Timer moveLeft();
  Timer mvoeRight();
  void stop();
}
The Timer return type for those move actions could likely be adapted to something more domain specific, but they will suffice for now. For example, the moveForward() action continuously moves the robot forward until the returned timer is canceled. So timer objects will work in this first pass at the pattern.

I will move the robot adaptee forward once a second, so I grab a reference to a one second constant:
const oneSecond = const Duration(seconds: 1);
With that out of the way, I am ready to adapt my robot to the universal remote robot interface.

The adapter will need to accept an instance of the Robot being adapted:
class UbotRobot {
  Robot _robot;
  UbotRobot(this._robot);
}
A moveForward() can then make use of that private instance variable reference to the robot to move it forward (or "north" in Robot parlance) once every second:
class UbotRobot {
  Robot _robot;
  UbotRobot(this._robot);

  Timer moveForward() =>
    new Timer.periodic(oneSecond, (_){ _robot.move(Direction.NORTH); });
}
To implement the other directions, I would likely use a common private method along the lines of _move():
class UbotRobot {
  Robot _robot;
  UbotRobot(this._robot);

  Timer moveForward()  => _move(Direction.NORTH);
  Timer moveBackward() => _move(Direction.SOUTH);
  Timer moveLeft()     => _move(Direction.WEST);
  Timer mvoeRight()    => _move(Direction.EAST);
  Timer _move(dir) =>
    new Timer.periodic(oneSecond, (_){ _robot.move(dir); });
}
With that, I am ready to try things out in the client code. I grab an instance of the robot being adapted to supply it to the universal remote robot adapter:
  var robot = new Robot();
  var universalRobot = new UbotRobot(robot);
Next, I start moving forward, making sure to grab a reference to the control object (the returned Timer):
  print("Start moving the robot.");
  var btnCtrl = universalRobot.moveForward();
To simulate waiting 10 second before releasing the button, I create a 10 second timer. When the 10 second timer has elapsed, the callback cancels the timer and prints the robot's new location:
  // Simulate the button being release 10 seconds later...
  new Timer(
    new Duration(seconds: 10),
    (){
      btnCtrl.cancel();
      print("The robot is now at: ${robot.location}.");
    }
  );
And that does the trick, my procedural robot moves north once every second, winding up at 0, 10:
$ /bin/play_robot.dart
Start moving the robot.
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
  I am moving Direction.NORTH
The robot is now at: 0, 10.
So in the end, a simple asynchronous adapter for procedural code was still pretty darn easy. Let's see what else I can throw at Dart to make this a little more difficult. Tomorrow.

Happy New Year everybody!

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


Day #50

Wednesday, December 30, 2015

An Object Adapter (Pattern) in Dart


It would have been fun to come up with a class adapter pattern in Dart. Sadly, the best that I could come up with is of very limited use. Even though I usually get in trouble when I say this, I suspect that the object adapter will be easy to implement. Let's see how much trouble that causes.

I am still working with generic implementation names for my classes. Target describes the simple interface that I am trying to support:
class Target {
  void request() {
    print("[Target] A request.");
  }
}
So all my adaptee needs to support is the request() method. Currently, however, it resides in a separate library over which I nominally have no control:
library adaptee;

class Adaptee {
  void specificRequest() {
    print("[Adaptee] A specific request.");
  }
}
In the sample code in the Gang of Four book, client code creates an instance of the adaptee to supply to the adapter. To follow along with that example, I need something along the lines of:
import 'package:adapter_code/adaptee.dart';
import 'package:adapter_code/adapter.dart';

main() {
  var adaptee = new Adaptee();
  var adapter = new Adapter(adaptee);

  // Invoke a target method, not available on the adaptee:
  adapter.request();
}
Then, to implement the adapter class, I need to accept an Adaptee argument in the constructor and define a request() method that, among other things, invokes a specific method on that Adaptee:
class Adapter extends Target {
  Adaptee _adaptee;

  Adapter(this._adaptee);

  void request() {
    print("[Adapter] doing stuff..");
    _adaptee.specificRequest();
  }
}
Of note, I extend Target rather than implement its interface. The end result is the same in this case since I redefine request. Still, this might come in handy should I need access to another helper method from Target.

Whoops! That's some premature generalization if ever there was some. I note that I could do that if needed, but, for now, I only implement the interface:
class Adapter implements Target {
  Adaptee _adaptee;

  Adapter(this._adaptee);

  void request() {
    print("[Adapter] doing stuff..");
    _adaptee.specificRequest();
  }
}
With that, I have my object adapter. Running the client code results in some work in the adapter and some in the adaptee:
$ ./bin/adapt.dart                                             
[Adapter] doing stuff..
[Adaptee] A specific request.
One of last night's laments—that the class adapter exposed the adaptee's methods publicly—is no longer applicable here. The only publicly supported method is request() from the target interface. Of course, the client code still has access to the adaptee's specificRequest() method via adaptee. The point is to maintain proper encapsulation, not to prevent access, so this is acceptable.

So for once I did not jinx myself. The adapter pattern in object form really is pretty darn easy. There are a couple of not-too-surprising implications (implement the target until extending is required, the adaptee is available in the client context, encapsulation is resolved), but this really went pretty much as expected. Darn it.

Maybe a specific case tomorrow will provide a little more excitement!

Play with the boring code yourself on DartPad: https://dartpad.dartlang.org/0cbca96caaa3ac9f95da.



Day #49

Tuesday, December 29, 2015

Class Adapters in Dart: A Vague Attempt


Time to pick another pattern to explore in Dart. Up today, the adapter pattern, a nice structural pattern as a change of pace from the behavioral ones that I have been exploring.

This is unique among the pattern in the Gang of Four book in that it has both class and object implementations described in the book. I should start with the object implementation because I think I understand how to implement it already. But where's the fun in that?

I am going to stick with abstract class names to get started. The Adaptee is the class that needs to be adapted to support an alternate interface. It would typically exist in a separate library since I could change it if it existed in a library that I could alter. Let's start with:
library adaptee;

class Adaptee {
  void specificRequest() {
    print("[Adaptee] A specific request.");
  }
}
Next, I have the interface that I need to support in the form of a Target class:
library adapter;

import 'adaptee.dart';

class Target {
  void request() {
    print("[Target] A request.");
  }
}
Presumably, I have a bunch of classes in this library that implement this interface. Now I need an adapter class that implements this interface, but still allows access to the methods in Adaptee. The class adapter approach used in the Gang of Four book uses multiple inheritance: public for the target interface and private for the adaptee interface. Dart does not support multiple inheritance (public or private). It supports multiple interface implementations, but that does not give me access to methods in both the target and adaptee.

I could try mixins—extending (subclassing) the target and mixing in the adaptee:
class Adapter extends Target with Adaptee {
  void request() {
    print("[Adapter] doing stuff..");
    specificRequest();
  }
}
That works... to a point. If I create an instance of the adapter in client code then access the request() method from the target:
main() {
  var adapter = new Adapter();
  adapter.request();
}
Then I get my desired output—the adapter request() method executes and then invokes specificRequest() from the adaptee:
$ ./bin/adapt.dart
[Adapter] doing stuff..
[Adaptee] A specific request.
There are two problems with this approach. First the adaptee's methods are now available publicly on the adapter:
main() {
  var adapter = new Adapter();
  adapter.request();
  // Can access adaptee methods from client code:
  adapter.specificRequest();
}
Which results in:
$ ./bin/adapt.dart
[Adapter] doing stuff..
[Adaptee] A specific request.
[Adaptee] A specific request.
The second problem is more serious. This will only work if the adaptee does not declare a constructor. If it does:
class Adaptee {
  Adaptee() { print("Adaptee!"); }
  void specificRequest() {
    print("[Adaptee] A specific request.");
  }
}
Then I get a warning:
[error] The class 'Adaptee' cannot be used as a mixin because it declares a constructor
Worse, I get runtime error:
$ ./bin/adapt.dart                                  
'package:adapter_code/adapter.dart': error: line 9 pos 35: mixin class 'Adaptee' must not have constructors

class Adapter extends Target with Adaptee {
                                  ^
In other words, this will not fly in all but extremely limited circumstances.

In the end, the best approach that I can think of is to implement the target interface and subclass the adaptee:
class Adapter extends Adaptee implements Target {
  void request() {
    print("[Adapter] doing stuff..");
    specificRequest();
  }
}
This is not ideal since the adaptee's specificRequest() is still public on the adapter class. If I really, really needed a class adapter, this might serve in a pinch.

That said, it seems like an object adapter is the only real option in Dart, so I will get to that tomorrow.

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


Day #48

Monday, December 28, 2015

Undoable Undo Commands and the Singularity


Anders Holmgren suggested a nifty implementation for the command pattern in Dart. Part of his solution has me flummoxed.

I do not think the problem is with Anders' solution. Having spent two days exploring it, I think it is solid. After last night, I do not believe the problem is with Dart either. I think the problem is mostly between my ears. That or I am experiencing the second of the two hardest things in programming:
  1. cache invalidation
  2. naming things
  3. off-by-one errors
The naming problem that I may be experiencing is that I have been working with objects of type Command. Anders solution used functions named Command while his classes were named CommandClass. So whenever his solution referenced Command, it meant the function, but I kept thinking the object.

This brings me to a question. When working with functions and function-like objects in Dart, how should I name them? Normally, I do not care for Hungarian notation. But I cannot think of anything better than calling one Command while the other gets the Hungarian treatment (either CommandFunction or CommandClass). I am not sure either is a good approach. Having already explored the other option, tonight I will explore how things look with a Command class and a CommandFunction typedef.

I should stress that I am not attempting to argue with Anders' solution. He adapted a working solution to my existing code, which I hugely appreciate. The working solution neatly sidesteps this naming issue. I may adopt that solution, but I first would like to see how this plays out. I also note that I strongly risk confirmation bias here—CommandClass confused me when I first looked at it and I named my class my original class Command. That said...

I start with a CommandFunction typedef:
typedef void CommandFunction();
My commands will all have void return type and take no arguments. Thus, any functions with that signature are "Command Functions". For example, the functions supplied to the "Hi!" and "Scare" buttons are both a CommandFunction:
  var btnSayHi = new Button("Hi!", (){ robot.say("Hi!"); });
  var btnScare = new Button("Scare Robot", (){ robot.say("Ahhhhh!"); });
In Dart, any class that declares a call() method is also a function. So any class that implements the abstract Command class will be a CommandFunction:
abstract class Command {
  void call();
}
The MoveNorthCommand, for instance, should be a CommandFunction:
class MoveNorthCommand implements Command {
  Robot robot;
  MoveNorthCommand(this.robot);
  void call() { robot.move(Direction.NORTH); }
  void undo() { robot.move(Direction.SOUTH); }
}
And indeed, when I check an instance of this class, it does report that it is a CommandFunction:
  var moveNorth = new MoveNorthCommand(robot);
  print("Is moveNorth and CommandFunction? ${moveNorth is CommandFunction}.");
This results in:
Is moveNorth and CommandFunction? true.
There is not much that I can do with the CommandFunction in my current implementation. The Command class cannot implement a typedef. Classes in Dart, even Function classes, can only implement other classes, not typedefs. So this means that Command is implicitly a CommandFunction, but there is no way to make that relationship explicit:
typedef void CommandFunction();

abstract class Command implements Function {
  void call();
}
What I can do, as I have done with the CommandClass approach, is replace references to Function with the CommandFunction typedef. Thus, a command in the Button class must be a CommandFunction:
class Button {
  String name;
  CommandFunction command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
    History.add(command);
  }
}
I can also constrain History so that it can only add CommandFunction objects:
class History {
  // ...
  static void add(CommandFunction c) {
   // ...
    _h._undoCommands.add(c);
  }
  // ...
}
While I am writing those, I have to admit that they do feel a little awkward. I want to talk about "command objects" or "command interface objects" instead of "command function objects." I can rationalize a little bit that these used to be "function objects" and the addition of "command" make the type clearer. But I honestly do not know if that stands up to the 6-months-later smell test. Regardless, I push on.

Currently, were I declare an UndoableCommand, it would implement the Command class (making it a CommandFunction) and add an undo() method:
abstract class Command implements Function {
  void call();
}

abstract class UndoableCommand implements Command {
  void undo();
}
I can replace Command as the implemented class in most of my commands with UndoableCommand without missing a beat. There are some other benefits as well, but where things get really interesting is with last night's typedef-as-a-generic-upper-bound solution.

This comes directly from Anders' solution and is pretty slick. Instead of declaring an undo() method in UndoableCommand, I make undo another command object:
abstract class UndoableCommand<C extends CommandFunction> implements Command {
  C get undoCommand;
}
As I found last night, I may not be able to extend a typedef in a class declaration, but I can do so in a generic. What this does is declare that the upper bound of the undoCommand has to be a CommandFunction. That is, I have explicitly constrained undoCommand to be a CommandFunction.

This allows me to rewrite my commands with commands that are themselves undoable commands:
class MoveNorthCommand implements UndoableCommand {
  Robot robot;
  MoveNorthCommand(this.robot);
  void call() { robot.move(Direction.NORTH); }
  UndoableCommand get undoCommand => new MoveSouthCommand(robot);
}
Just like replacing callbacks with objects in the original implementation the command pattern, this gives me more control and options with undo commands. Plus I can explicitly constrain these beasties to be CommandFunction thanks to the extended typedef. That remains small comfort since I cannot explicitly constrain the original Command class to be a CommandFunction. Still it's something.

As for the what gets the Command name question, I think I am going to give into confirmation bias here. I admit that CommandFunction got awkward in the History class, but I think that awkwardness was better than naming the typedef as Command and then mistaking it 6 months later for a command pattern object instead of a typedef. In the end, it is likely advisable to come up with different names altogether. Anders calls the typedef Callable in the working code, which is just another name for Function which might make it a bit too generic. Still, the resulting code reads nicely.

In the end, I think I finally have a handle on this. Big thanks again to Anders for the suggestion—undoable undo actions was a very worthwhile exploration. The typedef thing I could have done without (brain hurts!), but I should know it better... and now I do!

Play with the code in DartPad: https://dartpad.dartlang.org/61b96c6edfb1074c77f4.


Day #47

Sunday, December 27, 2015

On Second Thought, Extending Dart Generics


Extending Dart generics was new to me. And, having slept on it, I don't think I am a fan.

Following a suggestion last night, I briefly explored Dart generics as a way of limiting types in the command pattern. Do not mistake me here, I love the suggestion itself. As documentation, I think the generics suggestion works to a certain extent, though it was not obvious to me at first (perhaps it should have been so I'll let it slide for now).

So what is the particular implementation that has me bugged? It is extending a generic as in:
class ExtendedGenericB<T extends B> {
  T prop;
  ExtendedGenericB(this.prop);
}
What this says is that my ExtendedGenericB class supports type annotation when instances are created. The prop instance variable must be of whatever type is supplied and it has to be a B class or one of B's subclasses.

That is, if I have three classes, A, B which is a subclass of A, and C which is a subclass of B:
class A {}
class B extends A {}
class C extends B {}
Then my extended generic declarations says that prop, which gets its type from the generic, must either a B or a C type. And at first blush that seems to be the case.

If I declare an instance of ExtendedGenericB with type parameter of A (a superclass of the declared B upper bound for my generic):
  var a = new A();
  new ExtendedGenericB<A>(a);
Then I get a static type warning as expected:
[warning] 'A' does not extend 'B' 
For what it's worth, this is the relevant section (14. Generics) from the Dart spec:
A type parameter T may be suffixed with an extends clause that specifies the upper bound for T. If no extends clause is present, the upper bound is Object. It is a static type warning if a type parameter is a supertype of its upper bound. The bounds of type variables are a form of type annotation and have no effect on execution in production mode.
So all seems well, right?

Things start to get a little murkier if I change the type parameter on the instance from A to B or even C:
  // Why does this work?
  new ExtendedGenericB<C>(a);
I get no warnings here even though I am specifying a type C for the instance's prop value while supplying an object of type A.

The explanation for this is that Dart is not really statically typed. Rather its types are unsound. That is, I could assign C c = new A() and would see no warnings. I understand why this is the case, though when I run into it in live code, I usually have to give it some thought.

Things get really strange when setting the upper bound as a typedef, as I tried last night. If I declare A with a void-return-no-argument call() method:
class A {
  void call() {}
}
Then I have created a function class. That is, I could create an instance of A, as in A a = new A();, then call it like a function: a(). Since it is a void-return-no-argument function, I can describe it with a typedef:
typedef void Command();
Where this gets really mind-bendy is when extending a generic with a typedef, which actually works:
class ExtendedGenericB<T extends Command> {
  T prop;
  ExtendedGenericB(this.prop);
}
Now I can create an ExtendedGenericB with a class or function:
  var a = new A();
  // Works because Dart is unsound:
  new ExtendedGenericB<B>(a);

  // Works because class upper limits to a typedef
  new ExtendedGenericB<Command>((){ print('whoa!'); });
I have to admit that this is pretty cool. But I still find it hard to follow. I have a better grasp on it now that I have noodled it through. I remain skeptical that I would use it in real life and even more so that I would remember what it meant coming back to it six months later. That said, it seems interesting enough to allow to percolate another day or two before dismissing it to fringe coding practices.

Play with it yourself on DartPad: https://dartpad.dartlang.org/5e8eba316adb2bf03a8b.


Day #46

Saturday, December 26, 2015

Typedef and the Dart Command Pattern


I fancied myself done with the command pattern in Dart. Anders Holmgren had other ideas. In the comments on last night's "final" command pattern article, he had a number of insightful suggestions that I have yet to consider.

So consider I do, tonight.

First up, I had not been constraining my function or object commands. Just about everywhere I use commands, I allow it to be a generic Function:
class Button {
  String name;
  Function command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
    History.add(command);
  }
}
It should be noted here that any class that supports a call() method is a Function. So command here can be a function or function-like object.

As can be seen in the press() method, the function or object never takes any arguments. Furthermore, it never returns a value, so its return type should be void. Although the following Button would result in a run-time error, the Dart analyzer thinks that it is perfectly OK:
new Button("Test", (String arg) => "$arg $arg $arg");
The anonymous function should neither accept an argument nor should it return a value as it does with the hash rocket symbol.

Thankfully, Anders has me covered here. I should declare a typedef that describes my command interfaces:
typedef void _Command();
Anything with a type of _Command will now be required by the analyzer to return nothing and accept no arguments.

I replace all Function types with _Command, including in my Button invoker:
class Button {
  String name;
  _Command command;
  Button(this.name, this.command);

  void press() { /* ... */ }
}
Now the analyzer complains about my "Test" button:
[warning] The argument type '(String) → String' cannot be assigned to the parameter type '_Command'
So typedefs are a great suggestion.

What I would like to do next is replace the Function in the Command class declaration:
abstract class Command implements Function {
  void call();
}
I would like to explicitly tie my Command class with the void-no-argument _Command typedef:
abstract class Command implements _Command {
  void call();
}
That will not work however because:
[error] Classes can only implement other classes
I am not entirely out of luck, however. Even though there is no way to explicitly tie Command to my typdef, it is already implicitly associated. Any function-like thing that accepts no arguments and returns void is a _Command typedef. Thus:
abstract class Command implements Function { /* ... */ }
abstract class UndoableCommand implements Command { /* ... */ }
class MoveNorthCommand implements UndoableCommand {
  // ...
  void call() { robot.move(Direction.NORTH); }
}

main() {
  // ...
  var moveNorth = new MoveNorthCommand(robot);
  print("MoveNorthCommand is a _Command: ${moveNorth is _Command}");
}
Results in:
MoveNorthCommand is a _Command: true
So Dart already knows that anything implementing Command—or even declaring a void-no-arg call()—is a _Command.

In other words, there is no way to explicitly constrain a function class to a typedef interface... other than using a clever trick that Anders employs in the UndoCommand declaration. Even though I cannot extend or implement a typedef in a class declaration, I can extend a type in a generic:
abstract class UndoableCommand<T extends _Command> implements Command {
  void call();
  T get undoCommand;
}
The type of undoCommand is now restricted (upper-limitted?) to be a no-arg-void-return _Command. I remain unsure about that, however as it seems a bit... obscure. Why should it work to extend a generic type when extending the source class with the same thing does not? Regardless, it is certainly a nifty tool to keep in my toolbelt.

Much thanks to Anders for his pointers. I think I still have another point or two that I still need to cover. Tomorrow.


Day #45

Friday, December 25, 2015

Subclass Just to Support One Method?


I kinda like Dart mirrors.

As a long time dynamic language programmer, I didn't think that I would, but it can be quite pleasant. Other times, however...

In the code from last night's video, the call() method in the SimpleCommand class is nice:
import 'dart:mirrors';

class SimpleCommand<T> implements Command {
  T receiver;
  Symbol action;
  List args=[];
  SimpleCommand(this.receiver, this.action, [this.args]);
  void call() {
    reflect(receiver).invoke(action, this.args);
  }
}
This reflects on the object, then invokes a method with arguments. What could be easier or cleaner?

What I do not like is what I did with the History class, which holds a list of undoable commands in an application. The guard clause at the beginning of the add() method is too long and obtuse:
class History {
  // ...
  static void add(Function c) {
    if (!reflect(c).type.instanceMembers.containsKey(#undo)) return;

    _h._undoCommands.add(c);
  }
  // ...
}
What that line does is return when the command does not support an undo() method. That is, commands that cannot undo should not be added to this history list. It works, but...

I cannot work directly with the object mirror—there is no way for the object mirror in Dart to reflect on its methods or properties. So instead, I have to get a class mirror from the object mirror's type property. Then, I get a map of the supported methods with instanceMembers. Finally, I can ask if the list of instance members (methods) includes the undo() by asking if the map contains the #undo symbol. But I do not want to know if it contains the key—I want to know if it does not contain the key—so I have to go all the way back to the beginning of the expression to negate it.

I might simplify slightly by breaking parts out into helper methods or switching from a returning, negated guard clause to a curly-brace enclosing expression. Neither of those options really helps cut through the dense, hard-to-read code. I breezed through this implementation last night in the hopes that something better would appear today. Sadly, I cannot find anything in Dart mirrors that can make this any better.

I could switch my undoable command classes to support a different interface—UndoableCommand instead of Command:
abstract class Command implements Function {
  void call();
}

abstract class UndoableCommand implements Command {
  void call();
  void undo();
}
Then commands that support undo, like move-north, can implement this new interface:
class MoveNorthCommand implements UndoableCommand {
  Robot robot;
  MoveNorthCommand(this.robot);
  void call() { robot.move(Direction.NORTH); }
  void undo() { robot.move(Direction.SOUTH); }
}
Making use of that, my guard clause is much clearer:
class History {
  // ...
  static void add(Function c) {
    if (c is! UndoableCommand) return;

    _h._undoCommands.add(c);
  }
  // ...
}
That is much clearer than my mirror based approach. But I hate it.

It seems crazy to declare a class whose sole purpose is to describe that it supports a single method. Why not just ask it if it supports the method?

In the end, it is a good thing I punted this question until today. I finished the video and this certainly would have side-tracked me. I remain unsure what I would do if presented with this in live code. From a code maintainability perspective, I prefer the mirror approach (I'd likely put the obtuse path to the answer into a helper method). From a performance perspective, I would likely favor the subclass-just-to-support-one-method approach, avoiding mirrors. So it depends.

And last night's quick and dirty solution just might end up being my real solution in many instances.


Maybe you can come up with a better approach on DartPad! https://dartpad.dartlang.org/78fca73a983abe26476c


Day #44

Thursday, December 24, 2015

Video: Different Kinds of Commands in the Same Command Pattern (Advanced)


I am curious what a Design Patterns in Dart screencast series might look like. So tonight, I try my hand at the command pattern and the implications of multiple command types: regular command object, functions, and simple commands. Not much has to change in the pattern, but there are some definite gotchas...



I am still trying to figure this out, so feedback welcome!

Play with the editable DartPad: https://dartpad.dartlang.org/f0115c150d5d6ef6e4f6.


Day #43

Wednesday, December 23, 2015

Video: Macro Commands in the Command Pattern


I am curious what a Design Patterns in Dart screencast series might look like. So tonight, I try my hand at the command pattern and the implications of macro commands and, somewhat related, how much information should commands retain in order to restore state to receivers?



I am still trying to figure this out, so feedback welcome!

Play with the editable DartPad: https://dartpad.dartlang.org/afac45d45e047d64d6b2.


Day #42

Tuesday, December 22, 2015

Video: Multiple Receivers in the Command Pattern



I am curious what a Design Patterns in Dart screencast series might look like. So tonight, I try my hand at the command pattern and what is means to multiple receivers:



I am still trying to figure this out, so feedback welcome!

Play with the editable DartPad: https://dartpad.dartlang.org/ab4529ffc51cb1be6cac.


Day #41

Monday, December 21, 2015

Video: Undo in the Command Pattern


I am curious what a Design Patterns in Dart screencast series might look like. So tonight, I try my hand at the command pattern and undo:



I am unsure if this a valuable slice of the pattern to break off, so feedback welcome!

The editable DartPad of the final code: https://dartpad.dartlang.org/72cf687744281b69d7a0.

Day #40


Sunday, December 20, 2015

In Summary: The Command Pattern


So, the command pattern...

Maybe it's just easier to do this:



Also available at: https://youtu.be/EibupV6iwPw.

The DartPad for that code: https://dartpad.dartlang.org/cfde97d8a08c009ddf64.


Day #39

Saturday, December 19, 2015

Generic Commands


I can't figure out why the Gang of Four book used C++ class templates for simple commands in the command pattern. I understand how they could be used, but the why escapes me. Maybe it's a C++ thing.

Last night I was able to use Dart callback functions as simple commands. The GoF suggested callbacks as an alternative for commands, so I assume that there is no way to do something similar in C++. What I do not understand is why they needed a class template to generate classes for simple commands. Why not a single, simple class instead of class templates?

In the command pattern, the command links actions with receivers, so a very simple command might look something like:
class SimpleCommand implements Command {
  var receiver;
  var action;
  List args;
  SimpleCommand(this.receiver, this.action, [this.args]);
  void call() {
    // Call the action on the receiver here...
  }
}
To make that work in Dart, I need to use mirrors so that I can reflect on an object and invoke arbitrary methods:
import 'dart:mirrors';
// ...
class SimpleCommand implements Command {
  var receiver;
  Symbol action;
  List args;
  SimpleCommand(this.receiver, this.action, [this.args]);
  void call() {
    reflect(receiver).invoke(action, this.args);
  }
}
With that, I can create a simple command on the robot that I have been using as an example:
  // ...
  var moveNorth = new MoveNorthCommand(robot),
    // ...
    beSad = new SimpleCommand(robot, #say, ['Boo hoo.']);
I can then assign that command to an invoker (a button in this example) and tell the invoker to... invoke:
  // ...
  var btnUp = new Button("Up", moveNorth);
  // ...
  var btnTease = new Button("Tease Robot", beSad);

  btnUp.press();
  btnTease.press();
  // ...
That results in a sad robot:
[pressed] Up
  I am moving Direction.NORTH
[pressed] Tease Robot
Boo hoo.
I have to think that something similar to that is possible in C++. If type safety is the concern driving class templates, then I can get a little closer in Dart with generics. If I make my SimpleCommand class be for a specific type of receiver:
class SimpleCommand<T> implements Command {
  T receiver;
  Symbol action;
  List args=[];
  SimpleCommand(this.receiver, this.action, [this.args]);
  void call() {
    reflect(receiver).invoke(action, this.args);
  }
}
Then I can be assure myself that the receiver has the correct type assigned:
var
    // ...
    beSad = new SimpleCommand<Robot>(robot, #say, ['Boo hoo.']);
It is not exactly class templates, but nothing else in the pattern makes use of the command being a specific type—just that the command implement a common interface. In other words, I think this, along with last night's callbacks, is more than sufficient to serve as a simple command implementation in the command pattern.

I think that just about does it for the command pattern. I may review one more time tomorrow, or it may be time to throw a dart at another pattern for Design Patterns in Dart.

Play with the code in DartPad: https://dartpad.dartlang.org/26e623a65566e561af77.


Day #38

Friday, December 18, 2015

Simple Commands in a Complex Command System


I suffer an abundance of commands. I am trying to keep my exploration of the command pattern simple as I prepare for the corresponding entry in Design Patterns in Dart. My simple code has 10 commands:
  // Concrete command instances
  var moveNorth = new MoveNorthCommand(robot),
    moveSouth = new MoveSouthCommand(robot),
    moveEast = new MoveEastCommand(robot),
    moveWest = new MoveWestCommand(robot),
    danceHappy = new DanceHappyCommand(robot),
    startRecording = new StartRecordingCommand(camera),
    stopRecording = new StopRecordingCommand(camera),
    undo = new UndoCommand(history),
    redo = new RedoCommand(history);
I can likely eliminate several of those for a terser discussion, but this still begs the question, what the heck would I do with this in live code?

The problems is not so much the 10 instances of command objects. If there are 10 buttons in the UI (which is a problem for another book), then I need 10 commands. The trouble here is that I had to manually declare all 10 of those commands, each with varying degrees of complexity:
class MoveNorthCommand implements Command {
  Robot robot;
  MoveNorthCommand(this.robot);
  void call() { robot.move(Direction.NORTH); }
  void undo() { robot.move(Direction.SOUTH); }
}
The Gang of Four book suggests the use of C++ template classes to overcome class overload. As long as a command is simple enough (receiver + action, no undo), then C++ templates seems a nice solution. One template declaration can generate any number of simple command types.

There are no template classes in Dart. There is no way to dynamically generate a class at run or compile time. Either the class is hard-coded before compiling or it does not exist. So what are my options if I want to avoid command class explosion?

One option comes from the GoF themselves. They characterize commands as an object-oriented replacement for commands. Callbacks cannot support undo, but I only need a solution for simple commands, like making my robot say a word or phrase:
  var btnSayHi = new Button("Hi!", (){ robot.say("Hi!"); });
  var btnScare = new Button("Scare Robot", (){ robot.say("Ahhhhh!"); });

  btnSayHi.press();
  btnScare.press();
I have cleverly been naming my command execution method call(), which is what the Button's press() method invokes:
class Button {
  String name;
  Command command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
  }
}
Functions in Dart respond to call() by invoking the function. So this quick and dirty solution works:
$ ./bin/play_robot.dart
[pressed] Hi!
Hi!
[pressed] Scare Robot
Ahhhhh!
It works, but there are at least two problems. First is that the command property in Button is declared as a Command type. Supplying a function instead results in analyzer errors:
$ dartanalyzer bin/play_robot.dart lib/robot.dart
Analyzing [bin/play_robot.dart, lib/robot.dart]...
[warning] The argument type '() → dynamic' cannot be 
          assigned to the parameter type 'Command' 
(/home/chris/repos/design-patterns-in-dart/command/bin/play_robot.dart, line 34, col 36)
[warning] The argument type '() → dynamic' cannot be
          assigned to the parameter type 'Command' 
(/home/chris/repos/design-patterns-in-dart/command/bin/play_robot.dart, line 35, col 44)
2 warnings found.
I can get around this by declaring that the command property must be a Function:
class Button {
  String name;
  Function command;
  Button(this.name, this.command);
  // ...
}
And then declaring that the Command interface implements Function:
abstract class Command implements Function {
  void call();
}
That give me no type analysis errors:
$ dartanalyzer bin/play_robot.dart lib/robot.dart
Analyzing [bin/play_robot.dart, lib/robot.dart]...
No issues found
And my robot can still perform simple speech commands:
$ ./bin/play_robot.dart
[pressed] Hi!
Hi!
[pressed] Scare Robot
Ahhhhh!
The other problem with this approach is undo history. I specifically do not want to store these simple commands in my history since they do not support undo. I have yet to ignore these so they get added all the same. If I attempt an undo after making the robot speak:
  // ...
  btnUp.press();

  btnSayHi.press();
  btnScare.press();

  btnUndo.press();
  // ...
Then I get an exception from calling undo() on my callback command:
// ...
[pressed] Up
  I am moving Direction.NORTH
[pressed] Hi!
Hi!
[pressed] Scare Robot
Ahhhhh!
[pressed] Undo
Undoing Closure: () => dynamic
Unhandled exception:
Closure call with mismatched arguments: function 'undo'
I am adding to history in the button press() method:
class Button {
  String name;
  Function command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
    History.add(command);
  }
}
I can add a guard clause to the History.add() static method to prevent adding callback commands to the undo history. This is a little tricky for functions, however. First, I cannot check to see if the command is a Function because all my commands are now functions:
class History {
  // ...
  static void add(Function c) {
    // Nothing gets added now :(
    if (c is Function) return;

    // Add to singleton history instance
    _h._undoCommands.add(c);
  }
  // ...
}
Comparing the runtimeType is not much easier. The runtimeType of an anonymous function is not, in fact, Function:
class History {
  // ...
  static void add(Function c) {
    // Matches nothing, callback functions still get added :(
    if (c.runtimeType == Function) return;

    // Add to singleton history instance
    _h._undoCommands.add(c);
  }
  // ...
}
Oddly, even if I compare the runtimeType to the runtimeType of a actual function, I still do not get a proper guard clause:
class History {
  // ...
  static void add(Function c) {
    // Not equal for some reason, all callbacks still added to undo history :(
    if (c.runtimeType == (){}.runtimeType) return;

    // Add to singleton history instance
    _h._undoCommands.add(c);
  }
  // ...
}
What does work is converting the runtimeType to a String for comparison:
class History {
  // ...
  static void add(Function c) {
    // Both are '() => dynamic'
    if (c.runtimeType.toString() == (){}.runtimeType.toString()) return;

    // Add to singleton history instance
    _h._undoCommands.add(c);
  }
  // ...
}
With that, I have a relatively complex command pattern implementation that supports undo (and redo) history, yet still allows for very simple command definitions via callbacks. In the end it did not require too much effort. I may not have a full-blown class like a template might have produced, but this still seems an acceptable approach.

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


Day #37

Thursday, December 17, 2015

A Happy Dance for Macro Commands


I continue my exploration of the command pattern in Dart by examining macro commands. Macro commands are composites of other commands, which is one of the nice things about commands: that they can be combined.

I have a Robot class that moves in one of four cardinal directions defined in an enum:
enum Direction { NORTH, SOUTH, EAST, WEST }
Commands encapsulate movement in one of those directions along with the receiver of the command, the robot:
var moveNorth = new MoveNorthCommand(robot);
My button invoker class then links buttons with the appropriate command:
var btnUp = new Button("Up", moveNorth);
Which can be pressed to initial movement:
btnUp.press();
This all works thanks to the command pattern.

Today, I want to introduce the happy dance button. Its command will also link the robot to a command:
var danceHappy = new DanceHappyCommand(robot);
And a button will invoke this command when pressed:
var btnHappyDance = new Button("Happy Dance", danceHappy);
To make things interesting, I will make the happy dance a series of random steps. So I import dart:math and seed a random number generator:
import 'dart:math';

enum Direction { NORTH, SOUTH, EAST, WEST }

final rand = new Random(3);
With that, I am ready to dance. Using the raw enum is actually easier to implement than a macro command:
class DanceHappyCommand implements Command {
  Robot robot;
  DanceHappyCommand(this.robot);
  void call() {
    for (var i=0; i<8; i++) {
      robot.move(Direction.values[rand.nextInt(4)]);
    }
  }
}
But, since I am exploring macro commands, I switch to conditionally invoking the appropriate command instead:
class DanceHappyCommand implements Command {
  Robot robot;
  DanceHappyCommand(this.robot);
  void call() {
    for (var i=0; i<8; i++) {
      int r = rand.nextInt(4);
      if (r==0) new MoveNorthCommand(robot).call();
      if (r==1) new MoveSouthCommand(robot).call();
      if (r==2) new MoveEastCommand(robot).call();
      if (r==3) new MoveWestCommand(robot).call();
    }
  }
}
With that, I can move back to my client code to instruct the robot to happy dance:
btnHappyDance.press();
print("\nRobot is now at: ${robot.location}");
Which results in:
$ ./bin/play_robot.dart
[pressed] Happy Dance
  I am moving Direction.WEST
  I am moving Direction.WEST
  I am moving Direction.EAST
  I am moving Direction.WEST
  I am moving Direction.WEST
  I am moving Direction.NORTH
  I am moving Direction.SOUTH
  I am moving Direction.NORTH

Robot is now at: -3, 1
Yay! I am doing a happy dance of my own—that was fairly easy to do. But...

What about undoing that command? This is the command pattern, so I could rewind each command in the macro by invoking their respective undo() method. Instead, I think I will use this as an opportunity to record receiver state in an effort to return to that state as quickly as possible.

So, when the happy dance command is invoked, I make a note of the current x and y positions:
class DanceHappyCommand implements Command {
  Robot robot;
  int _prevX, _prevY;
  DanceHappyCommand(this.robot);
  void call() {
    _prevX = robot.x;
    _prevY = robot.y;
    for (var i=0; i<8; i++) {
      // 8 random moves here...
    }
  }
}
Using that information in an undo() method means that I can get back to the original starting point as quickly as possible:
class DanceHappyCommand implements Command {
  Robot robot;
  int _prevX, _prevY;
  DanceHappyCommand(this.robot);
  void call() {
     // ...
  }
  void undo() {
    var dir;

    dir = robot.x > _prevX ? Direction.WEST : Direction.EAST;
    while (robot.x != _prevX) {
      robot.move(dir);
    }

    dir = robot.y > _prevY ? Direction.SOUTH : Direction.NORTH;
    while (robot.y != _prevY) {
      robot.move(dir);
    }
  }
}
With that, I can instruct the client code to undo a happy dance:
  btnHappyDance.press();
  print("\nRobot is now at: ${robot.location}");
  print("--\n");

  btnUndo.press();
  print("\nRobot is now at: ${robot.location}");
Which results in a happy dance and a quick return back to my starting position:
$ ./bin/play_robot.dart
[pressed] Happy Dance
  I am moving Direction.WEST
  I am moving Direction.WEST
  I am moving Direction.EAST
  I am moving Direction.WEST
  I am moving Direction.WEST
  I am moving Direction.NORTH
  I am moving Direction.SOUTH
  I am moving Direction.NORTH

Robot is now at: -3, 1
--

[pressed] Undo
Undoing Instance of 'DanceHappyCommand'
  I am moving Direction.EAST
  I am moving Direction.EAST
  I am moving Direction.EAST
  I am moving Direction.SOUTH

Robot is now at: 0, 0
Although I might implement both call() and undo() differently in real life, these are still reasonable approaches. They have the added benefit of serving as nice talking points for the command pattern when I discuss it in Design Patterns in Dart, so I will call it a night here.

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

Day #36

Wednesday, December 16, 2015

Command History


So where does history get stored in the command pattern? The Gang of Four book only mentions in passing that the "application" holds the history. I wound up putting history in the command invoker as I was experimenting. That it is looking like a mistake.

The problem is my Dart invoker does more history management than it does invoking:
// Invoker
class Button {
  static List _history = [];
  static List _undoHistory = [];

  String name;
  Command command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
    _history.add(command);
  }

  static void undo() {
    var h = _history.removeLast();
    print("Undoing $h");
    h.undo();
    _undoHistory.add(h);
  }

  static void redo() {
    var h = _undoHistory.removeLast();
    print("Re-doing $h");
    h.call();
    _history.add(h);
  }
}
Do you see the code that actually invokes commands? Probably not without looking really close because of all those static methods.

It's never a good sign if you have a bunch of static classes and properties like that. My code is begging me to extract it out into a separate class, which I do:
class History {
  List _undoCommands = [];
  List _redoCommands = [];

  void add(Command c) {
    _undoCommands.add(c);
  }

  void undo() {
    var h = _undoCommands.removeLast();
    print("Undoing $h");
    h.undo();
    _redoCommands.add(h);
  }
  void redo() {
    var h = _redoCommands.removeLast();
    print("Re-doing $h");
    h.call();
    _undoCommands.add(h);
  }
}
With that, my button invoker is much, much nicer:
class Button {
  String name;
  Command command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
  }
}
Now I need to figure out how to get commands into history. Do I alter the press() method of Button to return the command so that client code can store history or do I make the invoker responsible for storing history. I opt for the latter, mostly because I do not want to clutter up my client code with a call to history.add() for each button press.

I do opt to convert the History class into a singleton and its add() method into a static method (static methods do have their place):
class History {
  // ...
  static final History _h = new History._internal();
  factory History() => _h;
  History._internal();

  static void add(Command c) {
    _h._undoCommands.add(c);
  }
  // ...
}
There is never a reason for more than one history object, so a singleton makes sense. Converting the add() method to a static method is a judgment call, but I wanted to be able to invoked History.add() when adding to history in the invoker:
class Button {
  // ...
  void press() {
    print("[pressed] $name");
    command.call();
    History.add(command);
  }
}
With that, I can get access to the history singleton in my client code and use it to undo and redo commands as much as I like:
  var history = new History();

  btnUp.press();
  btnUp.press();
  btnUp.press();

  history.undo();
  history.undo();
  history.redo();

  print("\nRobot is now at: ${robot.location}");
That does the trick as the robot code that responds to these commands moves three paces to the north (in response to three button-up presses), undoes two of those steps, then re-does one of the undoes:
$ ./bin/play_robot.dart                          
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
Undoing Instance of 'MoveNorthCommand'
  I am moving Direction.SOUTH
Undoing Instance of 'MoveNorthCommand'
  I am moving Direction.SOUTH
Re-doing Instance of 'MoveNorthCommand'
  I am moving Direction.NORTH

Robot is now at: 0, 2
For a grand total of 2 steps forward.

I am reasonably happy with the resulting code, but there is another benefit to making this change. I can now treat history as a command receiver in the command pattern:
  // Receivers
  var robot = new Robot();
  var camera = robot.camera;
  var history = new History();

  // ...
  var moveNorth = new MoveNorthCommand(robot),
    // ...
    undo = new UndoCommand(history),
    redo = new RedoCommand(history);

  // Invokers
  var btnUp = new Button("Up", moveNorth);
  // ...
  var btnUndo = new Button("Undo", undo);
  var btnRedo = new Button("Redo", redo);

  btnUp.press();
  btnUp.press();
  btnUp.press();

  btnUndo.press();
  btnUndo.press();
  btnRedo.press();

  print("\nRobot is now at: ${robot.location}");
The undo/redo commands only need to store the history instance so that they can call the appropriate action in response to a button press:
class UndoCommand implements Command {
  History history;
  UndoCommand(this.history);
  void call() { history.undo(); }
}
That history is itself a command now feels like a nice symmetry. In addition to the improved command implementation, I realize that I have an unfortunate habit of using static methods when writing exploratory code. I need to watch that or I am going to get myself intro trouble one of these days. But for today, I am safe.

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


Day #35

Tuesday, December 15, 2015

Redo Command


I have undo. So what about redo?

Over the past several days, I have explored undo in the command pattern in Dart, which leaves me a little curious about redoing / re-executing commands. I expect that they are fairly simple, but my expectations are rarely met in these matters. While I am at, I am still evaluating last night's robot command example as being worthy of using in Design Patterns in Dart—I worry that the robot example uses commands that are a bit too literal and is too simplistic.

Editable DartPad of last night's robot command example: https://dartpad.dartlang.org/3b2ac3f421db89c2b56a.

My first instinct with both undo and redo in this new example is to make them command buttons just like the other buttons on the "UI." This would allow me to press() these buttons just like the other buttons on the UI:
  btnUp.press();
  btnUp.press();

  btnUndo.press();
  btnRedo.press();
After considering this for a while, I think better of it. The undo and redo buttons look like the regular command buttons, but they do not behave that way. Specifically, regular command buttons store commands in history for… undoing:
class Button {
  static List _history = [];

  String name;
  Command command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
    _history.add(command);
  }

  static void undo() {
    var h = _history.removeLast();
    print("Undoing $h");
    h.undo();
  }
}
But I cannot invoke that same press() button lest the undo command get added to the undo history (the second of two undos would then attempt to undo the first, which is not right). I could create a fake button class specifically for these kinds of actions, except these fake buttons would wind up calling fake commmands:
    var undo = new UndoCommand(),
      redo = new RedoCommand();
These are not real commands in the command-pattern-sense because they do not associate a receiver with an action. The receiver of these action is the Button class. An undo command would just know this without having to be told:
class UndoCommand implements Command {
  void call() { Button.undo(); }
}
Admittedly, this is likely my code telling me that I should move history out of the Button class (what if a slider is added to the UI?). I will look into that another day. For now, I bypass the undo and redo buttons and just call those actions directly:
  btnUp.press();
  btnUp.press();
  btnUp.press();

  Button.undo();
  Button.undo();
  Button.redo();
With that out of the way, what of redoing?

The simplicity of commands for my robot makes undoing and redoing simple. The move-north command, for instance moves north when doing (or re-doing) and moves south when undoing:
class MoveNorthCommand implements Command {
  Robot robot;
  MoveNorthCommand(this.robot);
  void call() { robot.move(Direction.NORTH); }
  void undo() { robot.move(Direction.SOUTH); }
}
That is a fine implementation. I only worry about this in book format because it is so simple that it lacks the ability to illustrate the power of the pattern. Again, something to worry about another day.

After implementing similar undo() and redo() methods in the remaining command classes, I can teach the Button class how to use them. Undo is easy enough, but if I am to retain the option of re-doing and undone command, I need a place to store undone commands. Which means that I need a list of done commands and undone commands:
class Button {
  static List _history = [];
  static List _undoHistory = [];
  // ...
}
That aside, the first-pass implementation of undo() and redo() are simple enough:
class Button {
  static List _history = [];
  static List _undoHistory = [];
  // ...

  static void undo() {
    var h = _history.removeLast();
    print("Undoing $h");
    h.undo();
    _undoHistory.add(h);
  }

  static void redo() {
    var h = _undoHistory.removeLast();
    print("Re-doing $h");
    h.call();
    _history.add(h);
  }
}
That gets me what I want. If I move the robot 6 paces up/north, then undo two of those steps, then redo one of the undos:
  btnUp.press();
  btnUp.press();
  btnUp.press();
  btnUp.press();
  btnUp.press();
  btnUp.press();

  Button.undo();
  Button.undo();
  Button.redo();

  print("\nRobot is now at: ${robot.location}");
Then I wind up 6 - 2 + 1 = 5 paces to the north:
$ ./bin/play_robot.dart
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
Undoing Instance of 'MoveNorthCommand'
  I am moving Direction.SOUTH
Undoing Instance of 'MoveNorthCommand'
  I am moving Direction.SOUTH
Re-doing Instance of 'MoveNorthCommand'
  I am moving Direction.NORTH

Robot is now at: 0, 5
While that works, I definitely need to rethink where the history is stored. The Button class now has more history-related code than it does button-related code—a definite no-no. That coupled with my inability to support meta-buttons like undo/redo mean that tomorrow I explore retaining history in the application instead of the Button class. And maybe a happy random dance.

Play with the DartPad of the robot code so far: https://dartpad.dartlang.org/8fa8a3b4e0765e657e8a.


Day #34

Monday, December 14, 2015

Robotic Commands


My daughter loves BB-8 (yes, I'm that guy). She can't walk into my office without asking for her friend "BB." I think she could spend hours chasing him around.

At some point while mucking around with it, I realized that a robot controlled by a Dart application would a good example of the command pattern. In fact, I think it might be better example for Design Patterns in Dart than the Velvet Fog Machine that I have been using. Hard as it may be for me to accept, there are more folks familiar with robots than with Mel Tormé.

So tonight, I write an implementation of the command pattern for a robot. The command pattern has three components: the invoker, the receiver, and the command. The invoker in this robot example will be a button within an app. There will be multiple buttons for moving in different directions, executing macros, and capturing video. For the command receivers, I will stick with the robot and a camera. The commands will link the receiver with an action.

I find the Gang of Four book confusing when it includes an interface and the client code as "participants" in the pattern. There are three specific objects in this pattern, but the inclusion of these other two consistently makes me think that I am missing a participant. I'm sure it is just semantics, but an interface does not actively do anything in the pattern—it describes the methods that concrete commands must have.

Every application has a client, so it is hard to think of that as a participant—it is the context of the application, not a participant, darn it. That said, the client does participate in this pattern—it is responsible for associating commands with receivers. The robot and its camera are the receivers in this case:
// Client
main() {
  // Receivers
  var robot = new Robot();
  var camera = robot.camera;
  // ...
}
The commands could be a variety of directional movements and camera actions:
  // Concrete command instances
  var moveNorth = new MoveNorthCommand(robot),
    moveSouth = new MoveSouthCommand(robot),
    moveEast = new MoveEastCommand(robot),
    moveWest = new MoveWestCommand(robot),
    startRecording = new StartRecordingCommand(camera),
    stopRecording = new StopRecordingCommand(camera);
With that, the commands are linked with specific instances of the receivers.

There is nothing special about the Robot and Camera classes. Any class can be a receiver in this pattern and that is what they do here.

The command classes need to support a call() as the mechanism for executing concrete commands:
abstract class Command {
  void call();
}
For this particular case, the commands need to associate the receiver with the action:
class MoveNorthCommand implements Command {
  Robot robot;
  MoveNorthCommand(this.robot);
  void call() { robot.move(Direction.NORTH); }
}
The robot instance is assigned by client code. When this command is called, that robot instance moves north. The other direction command are identical save for the directions.

All that remains is the invoker. In this case, buttons in the UI will invoke commands. The buttons have names and are assigned commands, so the class definition is:
class Button {
  String name;
  Command command;
  Button(this.name, this.command);

  void press() {
    print("[pressed] $name");
    command.call();
  }
}
Back in the client, these are instantiated as:
  // Invokers
  var btnUp = new Button("Up", moveNorth);
  // ...
  var btnRecord = new Button("Record", startRecording);
  var btnStopRecord = new Button("Stop Recording", stopRecording);
That is all there is. I can press a bunch of buttons:
  btnUp.press();
  btnUp.press();
  btnUp.press();
  btnRight.press();
  btnRight.press();
  btnRight.press();
  btnLeft.press();
  btnDown.press();

  btnRecord.press();
  btnStopRecord.press();

  print("\nRobot is now at: ${robot.location}"
And, thanks to a few judicious print() statements, I see:
./bin/play_robot.dart                          
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Up
  I am moving Direction.NORTH
[pressed] Down
  I am moving Direction.EAST
[pressed] Down
  I am moving Direction.EAST
[pressed] Down
  I am moving Direction.EAST
[pressed] Left
  I am moving Direction.WEST
[pressed] Down
  I am moving Direction.SOUTH
[pressed] Record
  Capturing video record
[pressed] Stop Recording
  Video record complete

Robot is now at: 2, 2
So it works! And now that I see it... I am not quite as sure that I ought to use it instead of the Velvet Fog Machine example.

The commands feel too literal. They are quite explicit commands issued to a robot. Although that is a legitimate use of the command pattern, it has an artificial taste. I would prefer the examples in the book to be a bit closer to real-life examples. Sure, this kind of thing can happen, but the more interesting uses of the pattern occur when the commands are not obvious from the outset.

I will sleep on that. For now, here is the DartPad for further experimenting with the command and robots: https://dartpad.dartlang.org/3b2ac3f421db89c2b56a.


Day #33

Sunday, December 13, 2015

Repeating Undos in Command


My rather complicated command pattern has a bug. Perhaps my first instinct ought to be to simplify the implementation and maybe I will do that in the end. But first, I am going to see if I can fix the bug and, in doing so, see if this has something to say about my implementation of the pattern.

Last night's implementation on DartPad: https://dartpad.dartlang.org/efac76d03df17f6e3920.

The problem is in the undo operation. Complicating the undo is that some of the commands in my Dart implementation accept arguments:
  btnPlay.call(['It Had to Be You']);
  btnPlay.call(['Cheek to Cheek']);
  btnPlay.call(['At Last']);
  Button.undo();
I resolved a similar issue with these argument-commands the other night, but after some naming-inspired refactoring last night, the problem is back.

In the above, I am simulating a Mel Tormé aficionado playing songs on the velvet fog machine. The above script plays It Had to Be You, Cheek to Cheek, then At Last. While playing At Last, the Mel fan hits the undo button, which sends the song back to Cheek to Cheek. That still works:
$ ./bin/jukebox.dart
Play It Had to Be You
Play Cheek to Cheek
Play At Last
Undoing Instance of 'PlayCommand'
Play Cheek to Cheek
The problem occurs if I hit the undo button twice:
$ ./bin/jukebox.dart
Play It Had to Be You
Play Cheek to Cheek
Play At Last
Undoing Instance of 'PlayCommand'
Play Cheek to Cheek
Undoing Instance of 'PlayCommand'
Play Cheek to Cheek
Instead of playing At Last after the second undo, the velvet fog machine is still playing Cheek to Cheek.

My solution from the other night was to store the previous state information in the concrete command object—the PlayCommand in this case:
class PlayCommand implements Command {
  VelvetFogMachine machine;
  String _prevSong;

  PlayCommand(this.machine);

  void call([List args]) {
    _prevSong = machine.currentSong;
    machine.play(args.first);
  }

  void undo() {
    machine.play(_prevSong);
  }
}
Whenever the command is called, it first stores the current song being played, then tells the machine to play the requested selection. The whole point of the command pattern is to objectify the receiver (the velvet fog machine) and action (play), so this is all above board—I am not violating encapsulation.

This approach seemed to work the other night, but no longer. So what gives?

I initially thought this was caused by storing the history as a static property of the Button class:
class Button {
  static List _history = [];
  // ...
  void call([List args]) {
    command.call(args);
    _history.add(command);
  }
  // ...
}
That turns out not to be the cause. Instead, this is a pre-existing bug that I only noticed because of last night's reworking.

When the above code adds the command object to the history list, it is always adding the same instance when repeating commands. That is, multiple play button presses always send the same command to call():
  var btnPlay =
    new Button("Play", play);
  btnPlay.call(['It Had to Be You']);
  btnPlay.call(['Cheek to Cheek']);
  btnPlay.call(['At Last']);
To resolve this, I have to clone the command before adding it to the history list:
class Button {
  static List _history = [];
  // ...
  void call([List args]) {
    command.call(args);
    _history.add(command._clone());
  }
  // ...
}
That way, the previous song is remembered in the clone and not in the re-used instance.

Since there is no built-in clone() method in Dart, I have to make one of my own:
class PlayCommand implements Command {
  VelvetFogMachine machine;
  String _prevSong;
  PlayCommand(this.machine);
  // ...
  PlayCommand _clone() =>
    new PlayCommand(machine)
        .._prevSong = _prevSong;
}
With that, I am able to undo to my heart's content:
$ ./bin/jukebox.dart                                       
Play It Had to Be You
Play Cheek to Cheek
Play At Last
Undoing Instance of 'PlayCommand'
Play Cheek to Cheek
Undoing Instance of 'PlayCommand'
Play It Had to Be You
Although that does resolve my problem, I am not entirely satisfied. I have previously found that I need to clone receivers for similar reasons and now I have to clone commands. That is a lot of cloning to keep in order. I do not know if anything can be done to improve the situation. I think not, though I may take a look tomorrow. For now, I call this good enough.

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


Day #32

Saturday, December 12, 2015

What's in an Invoker Name?


I may be conflating concepts as I explore the command pattern for Design Patterns in Dart. Of course, I may perfectly OK in my current thinking, but tripping over terms in my mind lends doubt. So tonight I take a closer look at the invoker in the command pattern.

The invoker is the primary motivator in the pattern, so it behooves me to get it right. I like the menu item example in the Gang of Four book. It makes sense that actions need to be associated with menu items—that commands need to be associated with invokers. It then follows that the application (client) needs to instantiate these commands and associate them with menu items. The remainder of the pattern is the receiver and action of the action (e.g. the application receiver and the open action).

But I think the menu in my Velvet Fog Machine (it plays Mel Tormé, of course) is not quite right:
class Menu {
  List _history = [];

  void call(Command c, [List args]) {
     c.call();
    _history.add(c);
  }

  void undo() {
    var h = _history.removeLast();
    h.undo();
  }
}
Thanks to last night's efforts, that works just fine, but perhaps I should have stuck with the GoF's menu item instead of calling it a menu. Maybe it doesn't make a difference to the pattern. If nothing else, I have the feeling it would be a stronger example if it stuck to the menu item, so let's see.

If I were first approaching this problem, I would start not with the commands, but with the menu items on the velvet fog machine's user interface. There would be menu items for playing a single song and for manipulating playlists. When the code is initialized, it would have to associate these menu items with commands. Or, in Dart:
  // Invokers
  var menuPlay = 
    new MenuItem("Play", play);

  var menuPlaylistAdd = 
    new MenuItem("Add to Playlist", addFromPlaylist);

  var menuPlaylistRemove = 
    new MenuItem("Remove From Playlist", playlistRemove);

  var menuPlaylistClear = 
    new MenuItem("Clear From Playlist", playlistClear);
The commands do not change here, just the change from menu to menu-item. The resulting MenuItem class would then need to look something like:
class MenuItem {
  static List _history = [];

  String name;
  Command command;
  MenuItem(name, command);

  void call([List args]) {
    command.call();
    _history.add(command);
  }

  static void undo() {
    var h = _history.removeLast();
    h.undo();
  }
}
I am unsure about the history storage with this switch—that is likely a topic for another night. What I am sure is that the client code that follows now feels stronger to me.

If I were using the Velvet Fog Machine to play It Had to Be You, I would press the code for the song along with the Play button (note to self, maybe button here instead of menu item). I would expect that to be already associated with a command. With the previous Menu approach, I wound up calling the Menu instance with the command and the song:
  menu.call(play, ['It Had to Be You']);
  menu.call(play, ['Cheek to Cheek']);
Maybe that is still an acceptable implementation of the command pattern, but it seems awkward at the very least.

With the new MenuItem approach, a press of the Play button now results in calls like:
  menuPlay.call(['It Had to Be You']);
  menuPlay.call(['Cheek to Cheek']);
That makes me much happier. The difference between menu.call(play, ...) and menuPlay.call(...) may seem small, but it is much closer to the original description the GoF. Additionally, this new approach associates the command from the outset:
  var menuPlay =
    new MenuItem("Play", play);
Previously the application had to remember this association each time it needed to run the command.

I have a clearer picture now of the pattern. I also see the invoker-as-prime-mover as an important concept in the pattern. As an added bonus, I think I see a bug in undos that I was trying to find last night. So it looks like I will be back in undo land tomorrow.

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


Day #31

Friday, December 11, 2015

Multiple Command Undos


Do multiple receivers complicate life in the command pattern? My suspicion is that they do, but let's see.

I am still working with last night's VelvetFogMachine and Playlist receiver classes in Dart. Menu items from VelvetFogMachine's user inteface initiate commands that use these two receivers in order to aid in the assembly of the ultimate collection of Mel Tormé songs. Because everyone loves Mel.

From last night, the menu items supply arguments to the commands:
// ...
  menu.call(play, ['It Had to Be You']);
  // ...
  menu.call(addToPlaylist, ['Blue Moon']);
  // ...
My initial inclination here is that the history mechanism, currently residing in the Menu class, is going to need to remember these arguments:
class Menu {
  List _history = [];

  void call(Command c, [List args]) {
    if (args != null)
      c.call(args);
    else
      c.call();

    _history.add([c, args]);
  }
  // ...
}
But that is premature feature creep. For now, I stick with just adding the command to the undo history list:
    _history.add(c);
An undo can pop the last command off the list and invoke its undo():
class Menu {
  // ...
  void undo() {
    var h = _history.removeLast();
    print("Undoing $h");
    h.undo();
  }
  // ...
}
I will start by undoing the playing of the current song:
  menu.call(play, ['It Had to Be You']);
  menu.call(play, ['Cheek to Cheek']);
  menu.undo();
In this scenario, the velvet fog machine should stop playing Cheek to Cheek (something no self-respecting Mel fan would ever do) and revert to playing the previous song, It Had to Be You. I had thought the history would have to remember the song arguments, but I can now that I was wrong.

When the PlayCommand is run, it can be responsible for knowing the previous song, which it can get from the VelvetFogMachine:
class PlayCommand implements Command {
  VelvetFogMachine machine;
  String _prevSong;

  PlayCommand(this.machine);

  void call([List args]) {
    _prevSong = machine.currentSong;
    machine.play(args.first);
  }
  // ...
}
The undo() method can then tell the velvet fog machine to play that previous song:
class PlayCommand implements Command {
  // ...
  void undo() {
    machine.play(_prevSong);
  }
}
That does the trick. When I run the following commands:
  menu.call(play, ['It Had to Be You']);
  menu.call(play, ['Cheek to Cheek']);
  menu.undo();
The resulting output is:
Play It Had to Be You
Play Cheek to Cheek
Undoing Instance of 'PlayCommand'
Play It Had to Be You
Despite that success, I am still unconvinced that the history can do without the command arguments. Let's see what happens when I try to remove and item from the playlist:
  var playlist = new Playlist([
    '\'Round Midnight',
    'It Don\'t Mean A Thing (If It Ain\'t Got That Swing)',
    'New York, New York',
    'The Lady is a Tramp'
  ]);
  menu.call(removeFromPlaylist, ['New York, New York']);
  menu.undo();
  menu.call(play, [playlist]);
This turns out to be tricky, but not for any reason associated with the amount of information stored in history. Rather, the problem is one of reference vs. value variable assignment.

The problem arises when storing the previous playlist when the remove command is invoked:
class PlaylistRemoveCommand implements Command {
  Playlist playlist, _prev;

  PlaylistRemoveCommand(this.playlist);

  void call([List args]) {
    _prev = playlist;
    print('==> [remove] $args');
    playlist.remove(args.first);
  }
}
Since Dart passes arguments by reference, both _prev and playlist refer to the same object. So if the undo command tries to undo:
class PlaylistRemoveCommand implements Command {
  // ...
  void undo() {
    playlist.songs = _prev.songs;
  }
}
I am out of luck—_prev.songs is missing New York, New York.

To work around this, I have to add a clone() method to the Playlist that copies the values in the playlist:
class Playlist {
  List<String> songs = [];
  // ...
  Playlist clone() => new Playlist(songs.map((s)=> s).toList());
}
Updating the command's call() method to clone the playlist before storing it as a representation of the previous state should do the trick:
class PlaylistRemoveCommand implements Command {
  Playlist playlist, _prev;

  PlaylistRemoveCommand(this.playlist);

  void call([List args]) {
    _prev = playlist.clone();
    print('==> [remove] $args');
    playlist.remove(args.first);
  }

  void undo() {
    playlist.songs = _prev.songs;
  }
}
Now, undoing the remove:
  menu.call(removeFromPlaylist, ['New York, New York']);
  menu.undo();
Results in:
==> [remove] [New York, New York]
Undoing Instance of 'PlaylistRemoveCommand'
Play 'Round Midnight
     It Don't Mean A Thing (If It Ain't Got That Swing)
     New York, New York
     The Lady is a Tramp
So, at least for the examples that I have so far, the command objects are able to get enough information from their receivers when assembling undo information. The need for cloning receivers was not unexpected—the Gang of Four book specifically mentions this as being needed. So the answer to my original question seems to be that multiple receiver type really has no effect on the complexity of command pattern code.

I stop here for the night. Up tomorrow: I think that I have some naming issues with my menu items. I will take a closer look. Until then...

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


Day #30