I wish I got it right more!
Posts tagged Flex
commanding dawn
Jan 16th
Over the last few weeks I have been trying to improve the documentation for Dawn on its GitHub page. I am slowly making progress (hindered a little by starting a new job) but realise there are still some real weak spots. One area in particular is Dawn’s use of the command pattern. I built Dawn’s commands in a bit of a rush while completing the project that demonstrated the need for them, so have held back giving them too much formal documentation until I can clean them up and add a couple more key features. That said, I still find them very useful in their current state so thought I’d write this little post to give them more of an airing.
There are lots of good reasons for using commands in your applications. They are a proven solutuion for all sorts of common problems in client side development such as queueing, cacheing, batching etc. They are also very useful for performing business logic that spans multiple domains within an application, and thus belong in no one domain alone.
Why make another command library?
Enough of why commands are good (we all know that), why does Dawn contain its own flavour of this oh so common pattern? In turns out providing the command pattern is not a simple as it might seem in Actionscript, at least not if you have some design principles you intend to stick to. Most of the frameworks I have come accross in actionscript provide commands in a pretty similar way, the steps are somethings like this
- Create a new object that implements some ICommand interface
- implement the execute method, which takes some generic object as its argument. Find a way to get hold of any objects you need, perhaps a service locator (PureMVC) or a singleton (Caringorm)
- define some string or event (a string type field) that triggers the command
- configure the framework to trigger the command on the newly defined event (one-to-one mapping)
So what is wrong with that? How could that be better? It seems to me that those steps break a number of principles I think are fairly important, it also looks like a lot of work which could go wrong.
Take step 1. “Create a new object that implements some ICommand interface“. Everyone loves a bit of programming to interfaces! But there a snag here with Actionscript, that ICommand interface will have defined a type for its argument e.g.
interface ICommand{
function execute(event:FrameworkEvent):void
}
In actionscript there is no way for me to extend an interface and narrow the type of the argument, this for example would be impossible
interface MyCommand extends ICommand{
function execute(event:MyFrameworkEvent):void
}
What that means is that any commands I write that want to get information out of the event that triggered them are going to have to cast the argument! Type safety FAIL! I want to be able to write type safe commands that know the exact type of their arguments.
Step 2. “implement the execute method, which takes some generic object as its argument. Find a way to get hold of any objects you need, perhaps a service locator (PureMVC) or a singleton (Caringorm)” You can probably guess what I dont like about that. Commands are so valuable because they can encapsulate complex logic that involves a number of parts of an application. But commands are stateless (created each time they are executed) and tend to be created by the framework, so how can they get hold of the objects that they need to act upon? In most frameworks I have come across objects that need to be involved in commands either need to implement the singleton pattern – the enemy of testable code! Or register with a service locator, which adds new dependencies on the command to a service locator class and a random string against which the object may (fingers crossed) be registered against. I want my commands to have as few dependencies as possible, I dont want to have to rely on strings to get hold of the core actors in my system, and I certainly dont want to fall into the many traps thats singletons lay.
step 3. “define some string or event (a string type field) that triggers the command” Having created this command in framework X I now need to think about how to trigger its execution. I might have to create a new object that extends some base event to do this, or I may just have to choose a string name. I can just about deal with this step, I know that there is going to have to be something that triggers the command (I just dont think string or events are very good choices).
step 4. “configure the framework to trigger the command on the newly defined event (one-to-one mapping)” This is where the previous step starts to frustrate me. I have to TELL the framework that the object I just created is the one that will trigger the command. This will most likely look something like so
framework.registerCommand( MyThing.NAME, MyLovelyCommand );
There are a couple of things I don’t like about that, firstly it depends on developer discipline (I dont have that!), meaning it’s up to me to check that the value of MyThing.NAME is what it should be, the compiler won’t care if all my NAME properties have the same value!! Secondly it’s configuration, and configuration does not rock my boat.
how is Dawn different?
Heres an example of what a typical command might look like in Dawn (in a typical hay making application).
class MakeHayCommand{
[Inject] public var barn:Barn;
[Execute] public function execute( note:MakeHay ):void{
barn.makeHay(note.howMuchHay);
}
}
There are a few things to note
- there is no ICommand interface
- the argument to the execute method is specific to the business logic being executed
- the execute method has [Execute] metadata
- the barn variable has [Inject] metadata
You might have already guessed that a Dawn command was not going to implement an ICommand interface. Dawn tries to make the most of Actionscript by using metadata over interfaces here inorder to preserve type safety. When this command is triggered the method that has the [Execute] metadata will be invoked (this also means that we could call the method anything we like, something more meaningful, like, makeTheHay). Now that we have an argument that is specific to the business logic being executed we no longer need to perform risky runtime casting.
My other major gripe with commands is how core actors within a system are reached, Dawn makes this easy by building upon its dependency injection library. Just like any other object in Dawn, the command need only specify what it needs by providing the [Inject] metadata. Dawn will ensure that the relavent objects are constructed/retrieved before the command is executed, so all the logic to fetch domain objects via service locators or singletons is removed, making for a terser more testable command.
While all that type safety would be good on its own it also hands us another easy win with a bit of dry configuration. We (and Dawn) can see the type of the argument of the execute method, so we can completely skip the configuration step (thats the nasty bit where we start defining strings all over the place), the command is implicitly mapped to the MakeHay notification.
Setting up and triggering a command then looks much simpler
We tell Dawn we have a new command (but skip any mapping step)
commands.addCommand(MayHayCommand);
Since the command system is built on top of Dawns other libraries (DI and notifications) we can just send a notification of type MakeHay to trigger the command.
notificationBus.trigger(new MakeHay(numberOfBales));
and we’re done.
One more quick win
Another nice feature we get for free by building on top of the notification system is that any command you write is mapped by type, and types can be concrete classes (like the above example) or abstract classes or even interfaces.
Here is a command that will log any notification that implements IResponder
class LogRpcCommand {
[Execute] public function execute( responder:mx.rpc.IResponder ):void {
trace("making rpc call", responder);
}
}
Recap
Hopefully I’ve gone someway in justifying why Dawn implements it’s own command pattern. I wanted to ensure my code stayed type safe, I didn’t want to invent verbose ways of getting hold of objects within the system, and I didn’t want to map classes to string.
I still have someway to go with them, there is more I want from them (queueing baked in etc) but I already find them very useful, and well worth their place in Dawn.
Dawn at FLUG
Nov 18th
Last night I got the chance to give Dawn its public launch as I presented it at FLUG. Dawn is a set of libraries I have been developing to aid my actionscript development. It consists of three core parts
- A dependency injection library inspired by Google Guice
- A notification system based on types
- A simple type safe command pattern
I built Dawn to address a number of issues that I felt existed in many of the current approaches to application development for the Flash platform. I hope I went some way to demonstrating how I feel Dawn helps you write testable, type safe and agile code.
Thanks to all who attended and for the the positive feedback.
Below are the slides I used in the talk, or you can download the keynote file
Looking towards declarative interfaces in GWT
Jun 7th
I have been doing some work with GWT lately, and there is a lot I really like about it. Developing in Java (or any OO language) not only makes me more productive, it enables me to solve problems in the way I understand, without having first to grapple with how another language requires me to think. The output is awesome since its rendered natively in the browser, making it fast, and familiar. Basically there is a lot I really like about GWT, and I’m going to be using it wherever I get a chance from now on, but that not to say its all good.
Mini Gripe
I do have a mini gripe with the current implementation (well maybe I’ll have a few, but this one stands out), it’s the way interfaces are described in Java. For all Java’s benefits, it remains a verbose language, and developing UI structure with it looks clumsy and hard to maintain, in fact I know it is. I can say that with some confidence since development in GWT is almost identical to Flex development.
In Flex, if you try to develop all your interface in actionscript you end up in a similar situation. Classes quickly become very large (huge createChildren methods) as many nested components are instantiated and associated with one another. Fortunately this can be avoided in Flex, as its is better practice to construct your layout using xml, leaving the declarative part of interface development in the language that suits it. Xml is not just better for interface development because its declarative, it also lends itself to input from other disciplines since many types of developers and designer are used to html as the language of website structure.
Gripe Solved (soon)
That’s not the end of the story, as I learnt from the Google Wave: Under the Hood video, where a project named UiBinder is briefly mentioned. The project sounded like exactly what I am after, and means of defining GWT interface in xml. After a little hunting I found this document and this post. Which explain what UiBinder is and importantly where it is (currently only internal to Google, though shortly to be released to you and me, w00).
UiBinder, briefly
UiBinder, according to the docs is a “service to generate Widget and DOM structures from XML markup“. Which after reading the proposal (the document is a proposal for UiBinder as a GWT feature) I figured out basically means it does exactly what I was hoping. So how does it work?
(I’ve taken the code below out of the proposal document since I cant yet try this myself. humph)
First the interface is defined using XML
<!-- HelloWorld.ui.xml --> <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'> <div> Hello, <span ui:field='nameSpan'/>. </div> </ui:UiBinder>
This describes the interface for a a classic hello world component. What I particularly like about the approach is how this file is then used from the Java, there are no nasty inline script tags or clumsy code behind super classes. The template xml file is bound to the Java class explicitly.
public class HelloWorld extends UIObject {
interface MyUiBinder extends UiBinder{}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
@UiField SpanElement nameSpan;
public HelloWorld(String name) {
setElement(uiBinder.createAndBindUi(this));
nameSpan.setInnerText(name);
}
}
The first line of the constructor is the interesting one, the UiBinder method createAndBindUi is called passing in this as the argument. This constructs your UI components and assigns them to corresponding private variables within the class, making the next line where the text is assigned to the span possible without ever having to directly construct the SpanElement within the java.
What you end up with is a very elegant separation of layout from logic. Cant wait to get my hands on it!
If you don’t have much patience there are other options, if you take a look to the bottom of the UiBinder proposal there are some links to similar projects at the bottom, though I’ve yet to look into them.
Woo, I presented at Max
Dec 3rd
I gave my presentation at Adobe Max this morning on building Flex applications with PureMVC. It was a real privilege to get the opportunity to speak, and I hope those who attended found it useful.
I also feel fortunate that I had such a good topic to talk on, as that always makes it easier
so many thanks to Cliff for doing such a great job with PureMVC
In case anyone is interested I have uploaded the slides and the sample code…
code
slides (keynote)
slide (swf)