Showing posts with label adapter pattern. Show all posts
Showing posts with label adapter pattern. Show all posts

Friday, January 8, 2016

The Adapter and the Dependency Inversion Principle


The best code believes the Earth to be flat. Possibly balanced on the backs of 4 largish elephants riding a giant turtle through space.

As far as a flat earther is concerned, travelling from Prudhoe Bay Alaska to Cape Horn is literally a straight shot from the center of our disc world to the edge. And for 99% of human thinking on travel that is just fine — certainly better than calculating the distance along a 120° arc over the surface of a sphere with a radius of 6400 km. Earth roundness is important to airlines, astronauts, and spy satellites, but most daily human existence works just fine on a flat earth. In other words, a flat earth is a useful abstraction.

That abstraction would work equally as well on the Moon or other planets. We would think of it as a flat planet abstraction on Mars or Jupiter, but the principle would be the same. And regardless of the celestial body on which we currently reside, we would think that our current home is a flat planet. That is, we would not think that flat planet is a collection of things, some of which behave slightly more or slightly less flat. Each planet that we visit would be a flat planet in our minds.

All of this is to say that flat earthers have the dependency inversion principle down cold—well, as long as they don't really believe what they preach. The dependency inversion principle states:
  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend on details. Details should depend on abstractions.
For me, it helps to mentally replace "not depend" with "be willfully ignorant of." High level modules should be willfully ignorant of low-level modules. Instead of thinking about the curve of the planet as we travel, modules should flat-earth things. Similarly, the low-level details should fit the abstraction, but the abstraction should be willfully ignorant of the details of individual planets.

All of this brings me back to the adapter pattern. I have been playing with this pattern in Dart for the past week or so, and having an octarine time of it. Before moving on, it is worth noting that the adapter pattern is a way to support dependency inversion.

My universal robot remote control example holds the high-level module stuff in the remote control. Given a robot, the remote control wants to be able to move said robot forward as much as it likes:
  universalRobot = new UniversalRemoteRobot(robot);
  universalRobot
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward();
According to the dependency inversion principle, the remote should be willfully ignorant of the robot details. The universal remote control will have to control hundreds of different kinds of robots (lest they control us). As such, the remote control code has to willfully ignorant of the differences between Oscorp and Tyrell robots. A remote control that knows the tiny details of a hundred robots would require huge amounts of code.

So instead, the remote thinks of every single different kind of robot as an abstraction. That abstraction is the target in the adapter pattern:
/*** Target ***/
abstract class Ubot {
  String get xyLocation;
  void moveForward();
  void moveBackward();
  void moveLeft();
  void moveRight();
}
As far as the remote is concerned, all robots can move forward, backward, to the left and to the right. As long as all robots implemented this interface, we would be done as far as the dependency inversion principle was concerned: the high-level remote control treats robots as the abstraction defined in the abstract class, the remote control is willfully ignorant of the robot details, the abstract class is willfully ignorant of the robot details as well, and the individual robots would implement the abstraction.

But that is not the end of the story in this case. The Tyrell Corporation refuses to implement the same robot interface as does Oscorp, so another class is required to adapt each individual robot to our Ubot interface:
/*** Adapters ***/
class RobotAdapterToUbot implements Ubot {
  Robot _robot;
  RobotAdapterToUbot(this._robot);

  String get xyLocation => _robot.location;

  void moveForward()  { _robot.move(Direction.NORTH); }
  void moveBackward() { _robot.move(Direction.SOUTH); }
  void moveLeft()     { _robot.move(Direction.WEST); }
  void moveRight()    { _robot.move(Direction.EAST); }
}
This class is very much aware of the Ubot abstraction. As a low-level detail, it should be. At the same time, it does not flat-earth the Robot class. Its whole purpose is to adapt the low-level Robot to the abstraction. So if this adapter class cannot flat-earth Robot, doesn't it violate dependency inversion?

Well no. This is not a violation because the adapter and the robot are both low-level objects. In fact, they are at the same level, with the adapter serving as a thin wrapper for the adaptee.

I am glad to have noodled this through. I have yet to determine how to deal with concepts like the dependency inversion principle in Design Patterns in Dart. Do I include a separate chapter? Do I mention them in passing while discussing other patterns? I cannot flat-earth that, lest the book be incomplete. Regardless, it was fun looking at the relationship between the adapter pattern and the dependency inversion principle.

Or as some might put it, "Ook."

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


Day #58

Thursday, January 7, 2016

Delegating Mirrors Might Make Me Cry


There is a point at which programmers should leave well enough alone. That point and I have long quarrels typically ending with me saying something that I regret and then driving around for hours until I have cooled down sufficiently to apologize.

This is likely to be one of those situations.

After last night, my delegating, pluggable adapter is beautiful in Dart:
class UniversalRemoteRobot implements Ubot {
  var robot;
  UniversalRemoteRobot(this.robot);

  Ubot get _ubot {
    if (robot is Robot) return new RobotAdapterToUbot(robot);
    if (robot is Bot)   return new BotAdapterToUbot(robot);
    return new NullAdapterToUbot(robot);
  }

   dynamic noSuchMethod(i) => reflect(_ubot).delegate(i);
}
The constructor for the UniversalRemoteRobot class accepts an instance of some kind of robot and assigns it to the this.robot instance variable. The noSuchMethodMethod() method, which is available to any Dart object, delegates any unknown methods called on UniversalRemoteRobot objects to the appropriate adapter, as determined by the _ubot getter.

The delegate() method, which comes from the dart:mirrors library, makes maintenance of this code quite nice. The Ubot interface currently support four movement methods as well as a position getter:
abstract class Ubot {
  String get xyLocation;
  void moveForward();
  void moveBackward();
  void moveLeft();
  void moveRight();
}
Were that to change—if additional directions were added or cameras were supported—I would have to do nothing to my pluggable adapter. The delegate() would continue to merrily send those new actions to the appropriate adapter. I should be contented by this.

But...

Whenever a new kind of robot is supported, I need to define the appropriate Ubot adapter and remember to add the adapter to the _ubot delegating getter. That is not completely horrible, which is why I ought to leave this alone.

That said, I can rationalize a concern for the size of the getter. Right now, I only support robots from two vendors in my universal remote control for robots code. What happens when I have dozens of robot vendors to support? A hundred line getter won't be too pretty then. Worse, it will obscure the main focus of this class, which is delegating to pluggable adapters.

So I would like to dynamically choose the adapter. This is going to involve more mirrors, so I start by switching the _ubot getter to return a mirror instead of a regular instance:
class UniversalRemoteRobot implements Ubot {
  var robot;
  UniversalRemoteRobot(this.robot);

  InstanceMirror get _ubot {
    if (robot is Robot) return reflect(new RobotAdapterToUbot(robot));
    if (robot is Bot)   return reflect(new BotAdapterToUbot(robot));
    return reflect(new NullAdapterToUbot(robot));
  }

   dynamic noSuchMethod(i) => _ubot.delegate(i);
}
This also allows the noSuchMethod() declaration to use the getter right away, instead of having to reflect first.

Now for the fun stuff. To find the adapter class, I need a mirror on the current library. I cannot just say give-me-the-current-library, I have to reflect on an object in the current library (like this), find the class mirror via the type property, then ask for the owner (the library):
    LibraryMirror thisLibrary = reflect(this).type.owner;
I can already feel a good cry coming on.

I have been following the convention of naming the adapter classes <Adaptee Name>AdapterToUbot, so the adapter for the Robot class becomes RobotAdapterToUbot. Using that convention, I can determine the adapter class as:
    Symbol adapterClassName = new Symbol('${robot.runtimeType}AdapterToUbot');
That's not too horrible. This next bit is.

To find the class mirror for the adapter, I have to look it up in the map of all declarations in the current library:
    var adapterClass = thisLibrary.declarations[adapterClassName];
With that class mirror for the adapter, I can get a new instance mirror with the newInstance() method:
    Symbol constructor = new Symbol('');
    return adapterClass.newInstance(constructor, [robot]);
The empty constructor name is required so that newInstance() can also work with named constructors.

Putting it all together, the delegating adapter getter now looks like:
class UniversalRemoteRobot implements Ubot {
  // ...
  InstanceMirror get _ubot {
    LibraryMirror thisLibrary = reflect(this).type.owner;

    Symbol adapterClassName = new Symbol('${robot.runtimeType}AdapterToUbot');
    var adapterClass = thisLibrary.declarations[adapterClassName];

    Symbol constructor = new Symbol('');
    return adapterClass.newInstance(constructor, [robot]);
  }
  // ...
}
That works in the sense that the code runs and does what it is supposed to do. On some level, it also makes the code more maintainable, since I now only have to add a new <Adaptee Name>AdapterToUbot declaration. But this utterly fails to make the code more readable. My beautiful UniversalRemoteRobot class is now a mirrored mess. I do not want to even think how prefixed libraries might affect all of this.

I may leave this exploration path alone. It seems possible. I can clean it up some by moving this code out into an explicit delegator class. But I doubt that I can clean it up to the point that I can include it Design Patterns in Dart without confusing actual pattern discussion.

So if you'll excuse me now, I need to drive around weeping for a while.

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



Day #57

Wednesday, January 6, 2016

Dart Delegation


Nearly done exploring the adapter pattern, I would like to take one more look at delegation in Dart. Delegation has come in handy the past few days as I have explored pluggable adapters, but it has been informal delegation. I am curious if there are more formal approaches available.

The delegation that I have been using in in the constructor of my "universal remote robot" class:
class UniversalRemoteRobot implements Ubot {
  Ubot _ubot;
  UniversalRemoteRobot(robot) {
    if (robot is Robot) _ubot = new RobotAdapterToUbot(robot);
    else if (robot is Bot) _ubot = new BotAdapterToUbot(robot);
    else _ubot = new NullAdapterToUbot(robot);
  }
  // ...
}
The _ubot private instance variable holds the delegated robot instance. Since this has been exploring adapters, the delegate points to the appropriate class that adapts a robot to the interface used in this universal remote control packages.

I might clean up that constructor by moving it into a getter:
class UniversalRemoteRobot implements Ubot {
  var robot;
  UniversalRemoteRobot(this.robot);

  Ubot get _ubot {
    if (robot is Robot) return new RobotAdapterToUbot(robot);
    if (robot is Bot)   return new BotAdapterToUbot(robot);
    return new NullAdapterToUbot(robot);
  }
  // ...
That does eliminate an else if, which I always appreciate. Still, it is just a superficial change and does not really touch on delegation.

What I am most curious about is what to do with calling methods on the delegated instance:
class UniversalRemoteRobot implements Ubot {
  // ...
  String get xyLocation => _ubot.xyLocation;

  void moveForward()  { _ubot.moveForward(); }
  void moveBackward() { _ubot.moveBackward(); }
  void moveLeft()     { _ubot.moveLeft(); }
  void moveRight()    { _ubot.moveRight(); }
}
There seems to be some repetition there. It seems like it might be time for some mirror fun.

I import dart:mirrors, then delete the four move* methods. In there place, I declare an InstanceMirror getter and a noSuchMethod() method:
import 'dart:mirrors';

class UniversalRemoteRobot implements Ubot {
  // ...

  InstanceMirror get _botMirror => reflect(_ubot);

  dynamic noSuchMethod(i) {
    return _botMirror.invoke(i.memberName, []).reflectee;
  }

  String get xyLocation => _ubot.xyLocation;
}
The noSuchMethod() is available on all Dart objects. It receives an invocation mirror instance describing the arguments that were passed to non-existent method. In this case, I know that my four methods do not accept arguments, so I can ignore the list of arguments. I do need to know the specific movement method that was called, which is stored in memberName of the invocation mirror.

The last piece of the puzzle there is a mirror of the _ubot delegated adapter. The only way to call an arbitrary method on an object in Dart is through a mirror. So the _botMirror getter returns that mirror from the reflect() function in dart:mirrors.

With that, I have an instance mirror of my adapter, and can invoke whichever movement method was sent to the UniversalRemoteRobot instance:
  universalRobot = new UniversalRemoteRobot(robot);
  print("Start moving the robot.");
  universalRobot
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward();
  print("The robot is now at: ${universalRobot.xyLocation}.");
And that works just fine, thank you:
$ ./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.
I still need to handle that xyLocation getter method that is sent to the delegate. This means a conditional in the noSuchMethod() declaration to handle getters:
class UniversalRemoteRobot implements Ubot {
  // ....
  dynamic noSuchMethod(i) {
    if (i.isGetter) return _botMirror.getField(i.memberName).reflectee;
    return _botMirror.invoke(i.memberName, []).reflectee;
  }
}
With that, I have completely delegated the pluggable adapter methods from the delegator to appropriate adapater. That is nice, especially since it is only four lines of code, but... that is a dense 4 lines of code. Say, while I was looking through the Dart InstanceMirror documentation, I could not help but notice that there is a delegate() method. That could not possibly do exactly what I expect it to, could it?

In fact, it does just that:
class UniversalRemoteRobot implements Ubot {
  // ...
  dynamic noSuchMethod(i) => reflect(_ubot).delegate(i);
}
That is lovely. Simply lovely.

With that, I can write the entire delegator class in my pluggable adapter pattern as:
class UniversalRemoteRobot implements Ubot {
  var robot;
  UniversalRemoteRobot(this.robot);

  Ubot get _ubot {
    if (robot is Robot) return new RobotAdapterToUbot(robot);
    if (robot is Bot)   return new BotAdapterToUbot(robot);
    return new NullAdapterToUbot(robot);
  }

   dynamic noSuchMethod(i) => reflect(_ubot).delegate(i);
}
Making this even nicer is that, no matter what methods are added to the Ubot interface, this does not need to change in order to support it. I do not have to define new methods. I do not need any additional conditionals in noSuchMethod(). I like this very much.

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


Day #56

Tuesday, January 5, 2016

Extending... er, Implementing… er, Replacing Timer


The timer in my Dart implementation of the adapter pattern bugs me. More to the point, its very existence annoys me.

The asynchronous interface of the robot currently returns Timer instances for the various movement actions:
class UniversalRemoteRobot {
  // ...
  Timer moveForward()  => _executeControlledCommand(_ubot.moveForward);
  Timer moveBackward() => _executeControlledCommand(_ubot.moveBackward);
  Timer moveLeft()     => _executeControlledCommand(_ubot.moveLeft);
  Timer moveRight()    => _executeControlledCommand(_ubot.moveRight);
  // ...
}
This exposes the underlying implementation detail of the movement commands. I am moving procedural robots once per second with a periodic Timer. The outside world only need a command runner object to be used when canceling movement. The Timer class includes a cancel() method, so this works, but exposes too much information.

I have tried replacing the Timer with a quick subclass, but that has proven unsuccessful. Tonight, I take a closer look. This ought be easy, after all.

I start by defining a simple Runner class that subclasses Timer:
class Runner extends Timer {}
Even with that simple declaration, I get a bunch of warnings from the type analyzer:
[error] The generative constructor 'Timer(Duration duration, () → void callback) → Timer' expected, but factory found
[warning] Missing concrete implementation of 'Timer.cancel' and getter 'Timer.isActive'
[warning] The class 'Runner' does not have a constructor 'periodic'
All right, I understand that I need the periodic() named constructor, but what gives with the rest of that? Why do I need to implement cancel() again—can't the superclass' implementation handle that? And what's with that factory constructor warning...?

Oh, dear. I see what the problem is. All of the constructors in Timer are factory constructors. That means my subclass needs to define its own factory or generative constructors to implement Timer. Bother.

Well, not that much of a bother, I suppose, but I would have preferred a simpler extends than this, if only to keep any complexity out of the supporting code. In live code, minor complexity is no big deal. In illustrative code, it can be a discussion killer.

I may stick with vanilla Timer in the end, but let's see what it looks like. The lack of public constructors likely means that I can implement a Runner independent of Timer, but I will start by at least implementing the interface (the isActive and cancel() action are both useful for running commands):
class Runner implements Timer {
  Timer _t;
  Runner.periodic(Duration d, Function cb) {
    _t = new Timer.periodic(d, cb);
  }
  bool get isActive => _t.isActive;
  void cancel() { _t.cancel(); }
}
I still need a Timer instance to move my robots once a second. If Timer won't give it to me, I create my own instance variable. The two Timer methods can then delegate to this instance. I still need a regular, unnamed constructor. I can actually use a redirecting constructor here... and get a little fancy:
const oneSecond = const Duration(seconds: 1);

class Runner implements Timer {
  Timer _t;
  Runner(Function cb): this.periodic(oneSecond, (_){cb();});
  Runner.periodic(Duration d, Function cb) {
    _t = new Timer.periodic(d, cb);
  }
  // ...
}
My movement commands all take zero arguments while a periodic timer callback requires one argument (the timer, so it can be canceled). While redirecting the main constructor, I convert the supplied callback from a zero argument callback to a zero argument callback that is wrapped by a one argument function. This means I can create new command runners as: new Runner(command)).

That's nice. It is fun to play with redirecting constructors, but it is completely unnecessary in this case. I can remove the extends Timer constraint and make things much clearer:
const oneSecond = const Duration(seconds: 1);

class Runner {
  Timer _t;
  Runner(Function cb) {
    _t = new Timer.periodic(oneSecond, (_){ cb(); });
  }
  bool get isActive => _t.isActive;
  void cancel() { _t.cancel(); }
}
So, in the end, it was not a big deal replacing the Timer class with something similar, but a little closer to the domain. I do wonder why Timer only provides factory constructors. I would hazard a guess that this has to do with compiling to JavaScript and the underlying setTimeout() implementation. It may not be a big deal, but it is not something that just works™ like so many things in Dart. Thankfully, it only requires a little noodling through.


Day #55


Monday, January 4, 2016

The Coolest Command is Also the Dartiest


Something strange happened yesterday. I wrote some Dart code that just worked™.

OK, that's not too strange—Dart is designed to be familiar and easy to understand, after all. What's strange is that I did something that would not have worked in nearly any other language—passing a reference to the method of an object instance. I cannot recall if I knew this would work or if I wasn't thinking and just got lucky. Probably the latter, but either way, it worked.

This definitely will not work in JavaScript, for example. If I have a Robot class in JavaScript:
Robot = function(){
  this.x=0; 
  this.y=0;
}
Robot.prototype.getXyLocation = function() { 
  return "" + this.x + ", " + this.y; 
}
Robot.prototype.moveForward = function() { 
  this.y++;
}
Then I can create an instance of Robot and move it forward by calling the moveForward() method:
var r = new Robot();
r.moveForward();
r.getXyLocation();
// => "0, 1"
But I cannot grab a reference to the moveForward() method from r, call that reference directly, and expect it to update r:
var c = r.moveForward;
c();
r.getXyLocation();
// => "0, 1"
The r remains at 0, 1 because of this, of course. Undesirable or unexpected behavior in JavaScript always comes back to this.

In this case, c is a function—the same one defined on the Robot prototype. Invoking it did increment this.y just as it did in the Robot method, but the this inside c refers to the top-level client object. I could apply() or call() the c function with the appropriate this context:
c.call(r);
r.getXyLocation();
// => "0, 2"
By explicitly setting the method context with call() I am able to update r. But that's a pain, like just about everything dealing with this in JavaScript. If I wanted to pass that method in code, I would always have to pass it along with the object. In other words, I would need some explicit form of the command pattern.

But in Dart, that turns out to be unnecessary. I can define a similar Robot class:
class Robot {
  int x=0, y=0;
  String get xyLocation => "$x, $y";
  void moveForward() { y++; }
}
Then I can move the robot forward, tear off the method into a variable and move the robot forward using that variable method:
main () {
  var robot = new Robot();
  robot.moveForward();
  
  var c = robot.moveForward;
  c();
  
  print("The robot is now at: ${robot.xyLocation}.");
}
After that, the robot has moved forward twice:
The robot is now at: 0, 2.
It turns out that I should have remembered this. There was a minor brouhaha over this on the Dart list over the summer. These tear-off methods are closures built into the language. This is a pretty cool feature, so the kerfuffle was not over this, rather over a more generalized tear-off syntax.

If I wanted to tearoff a getter like xyLocation, for instance, I could not assign robot.xyLocation—that would assign the value of the getter. To obtain a reference to getter method, I would have to use robot#xyLocation:
main () {
  var robot = new Robot();
  var loc = robot#xyLocation;
  var c = robot.moveForward;

  // Regular method invocation...
  robot.moveForward();

  // Tear-off method invocations...
  c();
  print("The robot is now at: ${loc()}.");
}
It is a little strange to tearoff a getter and have to invoke it with parenthesis, but the main source of consternation was the hash symbol to obtain the tearoff. I would tend to agree with those that object to that particular syntax—it is uglier than the regular syntax and it it easy to confuse with Dart symbols which start with the hash symbol as well. Still, it is nice to know that it is possible should I ever need it.

More importantly, I think I have identified the Dartiest possible command pattern. I can't believe that I almost overlooked it!

Play with this on DartPad (the generalized/hash tearoff syntax is not supported): https://dartpad.dartlang.org/f3a717a9743953733de8.


Day #54

Sunday, January 3, 2016

Asynchronous Delegator Adapters and the Simplest Commands that Love Them


So, pluggable adapters in Dart (or any languages for that matter)... I think I finally understand them.

The strange thing is that plugable adapters discussion in the Gang of Four book make complete sense now. I never really understood that part of the adapter pattern chapter before. Maybe it's simply that my brain is incapable of processing UML diagrams. Whatever the reason, it makes sense now—hopefully the previous two night's posts can attest to that.

There is one thing missing in last night's delegating, pluggable adapter pattern: different delegator and adapter interfaces. I think it is likely perfectly acceptable for both delegator and adapter to implement the same interface. It probably helps to illustrate the pattern to have them implement two different interfaces.

So my universal remote control for robots needs an interface that can be adapted to multiple robots. The Ubot interface describes the interface:
/*** Target ***/
abstract class Ubot {
  String get xyLocation;
  void moveForward();
  void moveBackward();
  void moveLeft();
  void moveRight();
}
In my quest for robot control dominance, I currently have adapters for two different kinds of robots: the standard Robot class and the newer Bot class robots. Astromechs are next, but that's tale for another day. The adapters implement the Ubot interface:
/*** Adapters ***/
class RobotAdapterToUbot implements Ubot {
  Robot _robot;
  RobotAdapterToUbot(this._robot);

  String get xyLocation => _robot.location;

  void moveForward()  { _robot.move(Direction.NORTH); }
  // More move methods here...
}

class BotAdapterToUbot implements Ubot {
  Bot _bot;
  BotAdapterToUbot(this._bot);

  String get xyLocation => "${_bot.x}, ${_bot.y}";

  void moveForward()  { _bot.goForward(); }
  // More move methods here...
}
As of last night, the universal robot also implements the Ubot interface. Since it implements the same interface, all that it really does is delegate to the appropriate adapter in the constructor after which all methods invoke the method of the same name in the adapter:
/*** A common interface delegator ***/
class UniversalRemoteRobot implements Ubot {
  Ubot _ubot;
  UniversalRemoteRobot(robot) {
    if (robot is Robot) _ubot = new RobotAdapterToUbot(robot);
    else if (robot is Bot) _ubot = new BotAdapterToUbot(robot);
    else _ubot = new NullAdapterToUbot(robot);
  }

  String get xyLocation => _ubot.xyLocation;

  void moveForward()  { _ubot.moveForward(); }
  // More move methods here...
}
Tonight, I remove that common interface and switch back to an asynchronous version of the universal remote control. Previously, that had been the adapter in the pattern that I was using, now it becomes the delegator to the appropriate adapter:
class UniversalRemoteRobot {
  Ubot _ubot;

  UniversalRemoteRobot(robot) { _delegateRobot(robot); }

  void _delegateRobot(robot) {
    if (robot is Robot) _ubot = new RobotAdapterToUbot(robot);
    else if (robot is Bot) _ubot = new BotAdapterToUbot(robot);
    else _ubot = new NullAdapterToUbot();
  }

  // Asynchronous methods go here...
}
The asynchronous methods, which move the robot until the movement is canceled (by pressing stop, releasing the move button, the robot crashing, etc.), can still be implemented with Timer objects:
const oneSecond = const Duration(seconds: 1);

class UniversalRemoteRobot {
  // ...
  Timer moveForward() =>
    new Timer.periodic(oneSecond, (_){ _ubot.moveForward(); });
  // ...
}
That moveForward() method will start a timer that moves the adapted robot forward once every second. That is a little messy already, which will make the class messy once the other four directions are implemented. It would get even worse if I had to store the timer so that all active commands can be stopped:
class UniversalRemoteRobot {
  // ...
  Timer moveForward() {
    var t = new Timer.periodic(oneSecond, (_){ _ubot.moveForward(); });
    _activeControls.add(t);
    return t;
  }
  // ...
}
Doing that four times would be crazy. So I need to pass the command (receiver and action) to a helper method. That sounds like a job for the command pattern!

Except I would prefer to avoid using two patterns in the same example code. So do I send an anonymous function to a timer method?
class UniversalRemoteRobot {
  // ...
  Timer _executeControlledCommand(command) {
    var t = new Timer.periodic(oneSecond, (_){ command(); });
    _activeControls.add(t);
    return t;
  }
}
That helper would execute the command on the delegated/adapted robot, add the timer to a list, then return the timer so that it could be canceled. But anonymous functions? Mirrors? Actual command objects?

It turns out that there is a Dart command object that I neglected to cover in my first pass at researching the topic. I can simply pass the method and I get the receiver for free:
class UniversalRemoteRobot {
  // ...
  Timer moveForward()  => _executeControlledCommand(_ubot.moveForward);
  // Other move methods here...

  Timer _executeControlledCommand(command) {
    var t = new Timer.periodic(oneSecond, (_){ command(); });
    _activeControls.add(t);
    return t;
  }
}
I really am a JavaScript hostage. It never occurred to me that passing an object's method would bring the object along without having to resort to some call() or apply() calling context silliness. Who would have guessed that it would just work like one would expect?

Well, I should have expected that it would work. And work it does. Now in the client context, I can create either a Robot or a Bot:
  var robot = new Robot();
  // This works exactly the same:
  // var robot = new Bot();
And supply that to a new instance of UniversalRemoteRobot, starting it along the way:
  var universalRobot = new UniversalRemoteRobot(robot);

  print("Start moving $robot.");
  var btnCtrl = universalRobot.moveForward();
I can then cancel that 10 seconds later:
  // Simulate releasing the button after 10 seconds...
  new Timer(
    new Duration(seconds: 10),
    (){
      btnCtrl.cancel();
      print("The robot is now at: ${universalRobot.xyLocation}.");
    }
  );
With that, I have an — ahem — asynchronous, non-common interface, delegating class to pluggable adapters. Or something like that.

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



Day #53

Saturday, January 2, 2016

Delegated Pluggable Adapter Pattern


I am reasonably happy with last night's pluggable adapter pattern in Dart. But there are always nagging concerns.

My current solution builds a large registry of methods and arguments, organized by type. In this case, my pluggable adapters support a universal remote control for robots, so the registry is organized by robot class:
  static Map<Type, Map> _registry = {
    Robot: {
      'forward':  [#move, [Direction.NORTH]],
      'backward': [#move, [Direction.SOUTH]],
      'left':     [#move, [Direction.WEST]],
      'right':    [#move, [Direction.EAST]]
    },
    Bot: {
      'forward':  [#goForward, []],
      'backward': [#goBackward, []],
      'left':     [#goLeft, []],
      'right':    [#goRight, []]
    }
  };
I am a little concerned that this would grow past manageable state once the universal remote control supports more than a dozen robots or so. I also imagine that I will wind up adding conditionals for more than one type of robot in the various movement methods that I am adapting. Currently, they are a relatively clean mirror-based implementation:
  void moveForward() {
    var _ = _registry[_robot.runtimeType]['forward'];
    reflect(_robot).invoke(_[0], _[1]);
  }
But, like I said, I can see that getting messy after a while.

So instead, I try moving the adapted methods back into individual classes, one for each kind of robot. So the Robot adapter, which its move() method and direction arguments will look like:
class RobotAdapterToUbot implements Ubot {
  Robot _robot;
  RobotAdapterToUbot(this._robot);

  String get xyLocation => _robot.location;

  void moveForward()  { _robot.move(Direction.NORTH); }
  // other move methods here...
}
Similarly, the adapter for Bot, which sports go-* methods for movements will look like:
class BotAdapterToUbot implements Ubot {
  Bot _bot;
  BotAdapterToUbot(this._bot);

  String get xyLocation => "${_bot.x}, ${_bot.y}";

  void moveForward()  { _bot.goForward(); }
  // other move methods here...
}
I like this solution for cases in which there is variation in adaptee interfaces. For example, the Bot adapter supports a specialized xyLocation getter without having to perform a type check in a single adapter class.

These adapters need to support the same interface, Ubot in this case, so that a delegating class can invoke the same method regardless of adaptee. The delegating class will provide the object that gets used in client code. To start with, I make that delegating class implement the same Ubot interface:
class UniversalRemoteRobot implements Ubot {
  Ubot _ubot;
  UniversalRemoteRobot(robot) {
    if (robot is Robot) _ubot = new RobotAdapterToUbot(robot);
    else if (robot is Bot) _ubot = new BotAdapterToUbot(robot);
  }

  String get xyLocation => _ubot.xyLocation;

  void moveForward()  { _ubot.moveForward(); }
  // other move methods here...
}
This class sets the delegated adapter in the constructor based on the adaptee type. If UniversalRemoteRobot is constructed for a Robot, then the RobotAdapterToUbot is used. For a Bot, the delegated adapter is a BotAdapterToUbot. As long as new robot types are assigned adapters to the Ubot interface, it should be easy to add them—they just need to be delegated in the constructor.

This is, I believe, the exact structure of the second pluggable adapter from the Gang of Four book, though their example had the delegating class and the adapters supporting different interfaces. I may try something like that tomorrow. For now, it does not get much easier than having the moveForward() in the delegator invoke the same method in the delegated adapter.

With that, my universal remote control works exactly the same for Bot and Robot instances:
  var r = new Bot();
  // This works exactly the same:
  // var r = new Robot();

  var universalRobot = new UniversalRemoteRobot(r);
  print("Start moving the robot.");
  universalRobot
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward();
  print("The robot is now at: ${universalRobot.xyLocation}.");
I still think last night's mirror-based approach has its place—especially in situations where I am assured of simple method invocations on the adaptees. But this delegated pluggable adapter approach feels like a better all-purpose solution.

I will likely put that sentiment to the test. Tomorrow.

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


Day #52

Friday, January 1, 2016

What the Heck is a Pluggable Adapter?


Confession: I never understood a thing about pluggable adapters in the Gang of Four book. I have read that section on more than one occasion and not understood a damn word. So it seems like good grist for a blog post.

Part of my confusion is that I am not 100% clear on what is meant by the term. When first introduced in the book, a pluggable adapter describes "classes with built-in interface adaption." I am unclear on what "built-in" means and what gets it (the adapter or adaptee). Later, they describe a reusable widget that needs to work with similar objects even if they have different interfaces. I am going to focus on that second idea for now. Maybe I can figure out what they mean in the first definition for a follow-up post.

I am still working with my Robot Dart class that moves in different directions via a single move() method:
enum Direction { NORTH, SOUTH, EAST, WEST }

class Robot {
  int x=0, y=0;
  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;
    }
  }
}
A competing robot manufacturer might have a different robot movement API that looks like:
class Bot {
  int x=0, y=0;
  void goForward()  { y++; }
  void goBackward() { y--; }
  void goLeft()     { x--; }
  void goRight()    { x++; }
}
So how do I go about defining an interface that can work with either of these? I think that if I can answer that, I will have a pluggable adapter.

The universal remote control that I am building requires a target interface that looks like:
abstract class Ubot {
  void moveForward();
  void moveBackward();
  void moveLeft();
  void moveRight();
}
When I previously only needed to support the Robot class, I could do so with a plain-old adapter like:
class UbotRobot implements Ubot {
  Robot _robot;
  UbotRobot(this._robot);

  void moveForward()  => _robot.move(Direction.NORTH);
  void moveBackward() => _robot.move(Direction.SOUTH);
  void moveLeft()     => _robot.move(Direction.WEST);
  void moveRight()    => _robot.move(Direction.EAST);
}
One way that I can convert that to support the Bot class as well is to add a conditional to each move-related method:
class UbotRobot {
  var _robot;
  UbotRobot(this._robot);

  bool get isRobot => _robot is Robot;
  bool get isBot   => _robot is Bot;

  void moveForward() {
    if (isRobot) _robot.move(Direction.NORTH);
    if (isBot) _robot.goForward();
  }
  // ...
}
That actually does the trick. In the client code, I can now use a Robot interchangeably with Bot when instantiating the universal UBot instance:
  var robot = new Bot(); // new Robot() also works
  var universalRobot = new UbotRobot(robot);
Regardless of which robot is used, the movement commands work, thanks to the adapter:
  print("Start moving the robot.");
  universalRobot
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward()
    ..moveForward();
  print("The robot is now at: ${universalRobot.location}.");
With the loquacious Robot, this results in:
$ ./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.
While the taciturn Bot produces:
$ ./bin/play_robot.dart                                                    
Start moving the robot.
The robot is now at: 0, 5.
Both kinds of robots are controlled by the same universal remote class.

It would be a pain to maintain an adapter like this. When the next robot is supported, I would have to make changes to each method. Worse, each method would eventually grow to contain one line for every supported interface. Better is to create a registry that contains enough information to invoke the appropriate commands on the adaptees. I think this must be what the Gang of Four were talking about with the three different versions of pluggable adapters.

I am unsure that I understand each of the types that they discuss. I do understand... mirrors! So I import Dart mirrors and declare a registry with sufficient information to issue move commands to each type:
import 'dart:mirrors';

class UbotRobot implements Ubot {
  var _robot;
  UbotRobot(this._robot);

  static Map<Type, Map> _registry = {
    Robot: {
      'forward':  [#move, [Direction.NORTH]],
      'backward': [#move, [Direction.SOUTH]],
      'left':     [#move, [Direction.WEST]],
      'right':    [#move, [Direction.EAST]]
    },
    Bot: {
      'forward':  [#goForward, []],
      'backward': [#goBackward, []],
      'left':     [#goLeft, []],
      'right':    [#goRight, []]
    }
  };
  // ...
}
With that, I can reflect on the robot when invoking the appropriate movement method (with arguments):
class UbotRobot implements Ubot {
  // ...
  void moveForward() {
    var _ = _registry[_robot.runtimeType]['forward'];
    reflect(_robot).invoke(_[0], _[1]);
  }
  // ...
}
Happily, that works as desired. Don't believe me? Try the code on DartPad: https://dartpad.dartlang.org/09b8a2b1f6da874c7c68!

I think I have a idea of what pluggable adapters are now. I may explore the concept a little further tomorrow. Hopefully I can better understand those implementation discussions from the book now!


Day #51

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