Showing posts with label design-patterns. Show all posts
Showing posts with label design-patterns. Show all posts

Sunday, December 6, 2015

Command in Dart


Whilst messing about with the memento pattern, I often found myself tripping over the command pattern. The patterns are similar enough that I confuse them, but dissimilar enough that I ought know better than to get them mixed up. So, at the risk of overloading on behavioral patterns, tonight I start on the command pattern in Dart for the forthcoming Design Patterns in Dart.

Something about the traditional light switch example for command patterns leaves me cold. That said, it is traditional for a reason—it uses physical object from the real world nicely in the example. So I start with that.

The idea behind the command pattern is the ability to represent a command as an object. That object can then be queued, replayed, or undone at a later time. The "command" in the pattern includes both a thing being acted on and an action being performed on that thing. In the traditional light switch example, the "thing" is a light and the action is turning the light on and off.

The Light class is a simple Dart class with a single method to turn the bulb on or off. In command pattern speak, the Light is the receiver of the command:
// Receiver
class Light {
  void turn(String state) {
    print("Light ${state}");
  }
}
The command itself has one requirement—that any command being run against the receiver executes some change. Thus the base class for commands requires that implementations define an execute() method:
// Abstract command
abstract class Command {
  void execute();
}
With that, I can define concrete commands for the Light receiver:
// Concrete Command
class OnCommand implements Command {
  Light light;
  OnCommand(this.light);
  void execute() { light.turn('ON'); }
}

// Concrete Command
class OffCommand implements Command {
  Light light;
  OffCommand(this.light);
  void execute() { light.turn('OFF'); }
}
Both commands require the Light receiver and both effect change on that receiver in their respective execute() methods.

With the core of the pattern out of the way, I am ready to focus on the "invoker." In the light switch example, the switch is the invoker, which is where this real-world example breaks down for me. I cannot think of a smart switch that might need to remember previous changes in state or a complicated switch that needs to queue commands. I am overthinking it, I know, so before I travel too far down that avenue, I simply define the Switch as:
// Invoker
class Switch {
  List<Command> _history = [];

  void storeAndExecute(Command c) {
    c.execute();
    _history.add(c);
  }
}
The main purpose of the invoker is to execute the command. Here, it also stores the command for later undo.

That is the bulk of the pattern. The client code that uses the pattern needs an instance of the invoker and the receiver:
  var s = new Switch(),
    lamp = new Light();
The client also needs the commands that can be executed:
  var switchUp = new OnCommand(lamp),
    switchDown = new OffCommand(lamp);
With that, the invoker can turn the light on at any time:
        s.storeAndExecute(switchUp);
And it can turn it off at any time:
        s.storeAndExecute(switchDown);
In this example, the power of the pattern is limited to the storage of the command. If the invoker defines an undo() as:
class Switch {
  List<Command> _history = [];
  // ...
  void undo() {
    _history.
      reversed.
      forEach((c) { c.execute(); });
  }
}
Then previously executed switch states can be replayed in reverse order. There is more to the command pattern than undo. I will continue to explore that tomorrow.

Play with this code on DartPad: https://dartpad.dartlang.org/4530f9917cccbf8a2cbd.


Day #25

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

Saturday, June 21, 2014

Dart Factory Method Pattern


It's time to start laying the foundation for Design Patterns in Dart. There is still work to be done on Patterns in Polymer (especially the screencasts for “Extras” readers), but for a variety of reasons, I need to start exploring how I am going to approach a design patterns book.

I have vague plans for how I would like to organize the book. Some of those plans will work, others… not so much. One of my best laid plans is to include examples of each pattern from the wild—similar to the original classic. I am unsure how well that will work. It is difficult, at best, to find implementations of each pattern in the wild that are clean enough to lend support to a book narrative. Since Dart is so new, it will be that much more difficult to find such examples (though I have definitely seen more than a few).

Regardless, I might as well start somewhere, so tonight… I cheat.

I start with the Factory Method pattern. What makes this a cheat is the source of it in the “wild.” I first saw this in Dart when I used it while building the Hipster MVC framework to support part of the narrative in Dart for Hipsters.

I actually went out of my way to not refer to this as a pattern at the time, but I need to start referring to things with proper names—especially if I am going to write a book in which names are so important. So…

Hipster MVC provides an abstract creator class in the form of HispterCollection:
abstract class HipsterCollection extends IterableBase {
  HipsterModel modelMaker(attrs);
  String get url;
  // ...
}
The factory method in this class is modelMaker().

The concrete creator class comes from the dart-comics repository. The Comics class extends the HipsterCollection abstract creator class and implements the creator method:
class Comics extends HipsterCollection {
  modelMaker(attrs) => new ComicBook(attrs);
  get url => '/comics';
}
Dang, that's actually a pretty nice example. Event the return type from the abstract and concrete creator classes line up. The abstract class declares it as HipsterModel and the concrete class returns a new ComicBook instance, which is a subclass of HipsterModel:
class ComicBook extends HipsterModel {
  ComicBook(attributes) : super(attributes);
}
About the only thing missing is the ability to create instances of ComicBook from a class name instead of method. This is given as an example in the Gang of Four book (in Smalltalk). It is also something that I, coming from a Perl, Ruby, JavaScript, anything-but-Java background would have preferred to use when I first wrote Dart for Hipsters. But it was not an option at the time since Dart lacked support for mirrors.

Now that Dart has some pretty nice support for mirrors, this ought to work just fine. And so I will tackle that tomorrow.



Day #100