These things are never done, but here’s my first cut at a Cairngorm 3 / Parsley application (view source enabled):

Some code and design ideas were borrowed from insync, others from cafe townsend.

It’s a rough cut, but not terrible. It uses Parsley model injection, commands and an event interceptor (when you try to place a bet and you’re not logged in, it prompts you to log in), Flex 4 skinning and is localizable. I added some navigation features, but think I’d need to use something like SWFAddress for deep-linking. It does not have unit testing, but I wrote it to be testable (with business logic in commands).

On my wish list:
– Deep linking through the URL.
– Using the Task Library so that after the user is successfully saved, the bet result event is sent.
– Unit testing.
– A coin flipping animation (which raises additional questions about how to synchronize events and view states)…

One way this deviates from the Cairngorm 3 guidelines is that it does not use the Presentation Model pattern. I decided against this for two reasons. First, the client I was learning this for does not use this pattern. Second, it seemed like an unnecessary layer of decoupling. If you use skins and the Presentation Model, the decoupling starts to get a bit ridiculous: for every view element you’d have a Presentation Model, a SkinnableComponent and a Skin, with the business logic contained in commands. Finally, there’s some data (such as the currently logged in user) that seems to belong in an application model rather than a presentation model – why tie it to a particular view component?

Events are separated into two categories: view events (which I prefix with “UI”) that are handled by top components, and application events which are handled by commands. For example, when the user clicks on a number to place a guess, a UIGuessANumberPickEvent is dispatched. Following the principle that only top-level components should dispatch application events, the GuessANumberPage component handles this event by dispatching the application event UserGuessANumberEvent. This is then handled by the dynamic command UserGuessANumberCommand. It’s kind of a lot of code for something so simple, but it follows a pattern, and allows for eventually testing the business logic.

There are two ways you can dispatch events so that the Parsley IOC can route them to commands. One way looks like this:

    [Event(name="guessFlipACoinWon", type="")]
    [Event(name="guessFlipACoinLost", type="")]
    public class UserGuessFlipACoinCommand extends EventDispatcher
        public function dispatchSave():void
            dispatchEvent(new SaveUserEvent(SaveUserEvent.SAVE, updatedUser.userVO));

The other way is this:

    public class UserGuessFlipACoinCommand
        public var dispatcher:Function;

        public function dispatchSave():void
            dispatcher(new SaveUserEvent(SaveUserEvent.SAVE, updatedUser.userVO));

I strongly prefer the second way. It’s more readable and vastly less brittle, since metadata has no error-checking.

There’s an architectural problem with this code that seems pretty endemic to the pattern itself: the LoginModel is essentially a global that can be injected anywhere, and the currentUser setter is public. This is not nearly as bad as making the currentUser a global variable, since at least there’s only one function that can modify the currentUser, but it’s not ideal. What I’d really like to do is have the setter only accessible to LoginCommand. One possibility would be something like this:

    public class LoginModel extends EventDispatcher
        private var _currentUser:User;

        // read-only bindable getter for the model's state
        public function get currentUser:User():String
            return _currentUser:User;

        public function setCurrentUser(value:user, command:LoginCommand):void
            if (_currentUser:User!= value)
                _currentUser:User= value;
                dispatchEvent(new Event("currentUserChanged"));

The idea is that the LoginCommand could set the current user by passing ‘this’ as the second parameter. Of course, anyone could call it like so: setCurrentUser(whateverUser, new LoginCommand()), so it’s not bulletproof. Also, it might complicate testing somewhat. Still, it would make for slightly more robust code.

Feedback welcome! Thanks.


The StyleManager has gone through some changes in Flex 4, primarily (it appears from my very cursory poking around) to support different modules having different CSS definitions.

So that’s a nice thing. There is one subtle and obscure change, though, involving class style declarations. Let’s say you want to programmatically change the colors of all your tooltips. The following, which worked under Flex 3, does not work under Flex 4. The variable css will be null every time.

var css:CSSStyleDeclaration = styleManager.getStyleDeclaration("Tooltip");

The  fix is easy: you need to include the namespace as well.

var css:CSSStyleDeclaration = styleManager.getStyleDeclaration("mx.controls.Tooltip");

That is all.

Jens Halm at spicefactory helped clear up some confusion on my part. If you declare a command using <DynamicCommand> in your context file, you should not also use metatags like [CommandResult] in your command class. I had done this, and was finding that result() was being called twice.

Bugs in my parsley…

February 4, 2011

The dependency injection in Parsley is nice when it works, but what do you do when your objects aren’t configured properly and you get an error like this?

Error: Error in message receiver
at org.spicefactory.parsley.core.messaging.impl::DefaultMessageProcessor/unhandledError()[I:\Spicefactory\Parsley\parsley-core\org\spicefactory\parsley\core\messaging\impl\]
at org.spicefactory.parsley.core.messaging.impl::DefaultMessageProcessor/handleError()[I:\Spicefactory\Parsley\parsley-core\org\spicefactory\parsley\core\messaging\impl\]
at org.spicefactory.parsley.core.messaging.impl::DefaultMessageProcessor/proceed()[I:\Spicefactory\Parsley\parsley-core\org\spicefactory\parsley\core\messaging\impl\]

There’s the brute force approach: just comment stuff out until it stops breaking, then you know where the issue is. This is crude, time-consuming and problematic…what if you forget to uncomment the code out? This happened to a client of mine recently.

You can step it up by configuring logging for Parsley. I added the following to my application’s <fx:Declarations> block:

        <mx:TraceTarget id="logTarget"

With logging on, I learned a little more about my error, namely:
Caused by: Error: Unsatisfied dependency: Context does not contain an object of type mx.rpc.remoting::RemoteObject

Better, but where exactly in my code is this occurring?

Time to step it up again and enable source code level debugging. First, you need the source code. I selected “Import…” then “Checkout Projects from SVN” and checked out This gave me an error at the end, but it didn’t really matter for my purposes.

Once I got the source code, I edited my project’s settings, went to Run/Debug Settings and edited my main application’s launch configuration to add the Parsley folder to the Source path (with ‘Search subfolders’ checked).

So, next I just searched for where “Unsatisfied dependency: Context does not contain an object” messages were thrown and set breakpoints wherever they occur. Long story short, I stopped inside ObjectTypeReference.resolve() and worked my way up the call stack to find that the problem was with my “SaveUserCommand” class that had this erroneous declaration:

        public var service:RemoteObject;

Well, that was a little annoying, but a good “learning moment.” Moving on…

Now that I’ve gotten my data all organized, I need to get it connected, and of course I’ll be using Dependency Injection.

Parsley offers a nice way to inject dependencies through the [Inject] metatag, but I found it tricky to get working. There’s some magic with what Parsley is doing under the hood, and one of these days I’ll try to figure it out, but for now, here’s what worked for me.

In my application file (SharkysCasino.mxml) I have:

        <spicefactory:ContextBuilder id="contextBuilder">
            <spicefactory:FlexConfig type="{SharkysCasinoContext}"/>
            <spicefactory:ViewSettings autowireComponents="true"/>

In my configuration file (SharkysCasinoContext.mxml) I have:

        <!-- declare the various view and model components so that Parsley can handle injection properly -->
        <spicefactory:View type="{MainView}"/>
        <spicefactory:Object type="{LoginModel}"/>

And in my view class ( I have:

        public var loginModel:LoginModel;

Although you probably should write code so this isn’t an issue, loginModel appears to be null until MainView is added to the stage.

Hope some of you got the reference…

My last post was all about the challenges I encountered getting the Cairngorm 3/Parsley insync-basic application to properly build and run. Now I have what should be a helpful model for creating new Cairngorm 3/Parsley apps.

Now finally to the fun stuff: code architecture.

There’s not a whole lot of data this program will need to deal with. It pretty much comes down to one class:

package net.flexpla.sharkys.domain
	public class User
		public var id:int;

		public var balance:int;

		public var email:String;

		public var name:String;

		public var password:String;

(Incidentally, I had to dig a bit before I found this page and discovered how all the cool kids were posting their code. One tip: switch to HTML editing before pasting your code, otherwise you lose your indenting).

So, somewhere in my program I’ll have a line like this:

	public var loggedInUser:User;

The only question now is where to put it. In Cairngorm 2, I’d just create a ModelLocator subclass and put the loggedInUser variable in there. I’d do this thinking “what a convoluted way to declare a global variable!” and “shouldn’t this be called a ModelSingleton or something?”, but I’d hold my nose and use the ModelLocator pattern because I’d be working with code built on Cairngorm 2, and the only thing worse than a bad pattern is an inconsistent use of patterns.

Cairngorm 3 stresses the use of Presentation Models, so I first figured I’d be putting it in a PM, something like LoggedInUserPM. But I cooled on this approach for several reasons:

  • The idea of separating presentation data and logic from the visual presentation is great, but that already seems to be covered under the SkinnableComponent/SparkSkin architecture.  Introducing the PM pattern seems to mean either having three classes per view, or dropping the skin. I don’t want to drop the skin.
  • The currently logged-in user doesn’t really seem to fall under “presentation data” , unless it goes in the Application’s PM. This would conflict with another Adobe suggestion, which is not to have hierarchical PMs.
  • It turns out that a client that I will most likely work with soon doesn’t use the PM architecture.

Maybe there’s some confusion on my parent, because I was thinking that “Presentation Model” was a pattern that replaced the Cairngorm 2 ModelLocator pattern. I don’t think it really does, since it’s really only ideally suited to presentation data. It doesn’t make sense to organize your application data into buckets based on where they will be displayed, particularly when some of that data may ripple throughout the entire UI.

So I need some kind of model to hold the logged in user, and I won’t be using either a PresentationModel or the Cairngorm 2’s ModelLocator. The simplest, cleanest approach seems to be what’s used in the Parsley version of Cafe Townsend: just have several models that are derived from Object and instantiated through your application’s configuration. The next question is where to locate this model within my application. Using the Cairngorm 3 recommended layering, my choices are Presentation, Application, Domain and Infrastructure. Adobe’s summary of these different layers is thin to say the least, and seems to suggest that if I want to understand them I should read the book “Domain-Driven Design” by Eric Evans. Since a picture is worth a thousand words, here’s a diagram from that book…

I’m nearly brilliant enough to make any sense of that, and since I’m a learn-by-example guy, here’s what I see in the insync application:

  • Presentation: contains presentation managers, components and skins
  • Application:  contains events, commands and controllers.
  • Domain: contains model classes.
  • Infrastructure: contains server related stuff.

I’m getting closer, but it’s still not obvious to me where the loggedInUser should go. Yes, into something like domain \ LoggedInUserModel. But isn’t there a fundamental difference between the User class and the LoggedInUserModel class? One is a data object that’s stored in a database, while the other just maintains state. Okay, I’m going nuts here. Time to move on. Here’s my structure.

  • src
    • (default package)
      • SharkysCasino.mxml
      • SharkysCasinoContext.mxml
      • SharkysCasinoTestRunner.mxml
    • net.flexpla.sharkys
      • application
        • commands
        • controllers
        • event
      • domain
        • data
        • state
      • infrastructure
        • delegates
        • services
        • vos
      • presentation
        • components
        • skins

I feel a little sad I spent so much time thinking about all this when I could have been playing with my son or something, but hopefully I won’t have to think about this again for a long time. It’s making sense to me. And I’m glad to have considered Presentation Models and decided for several reasons not to use that pattern.

However, I would love to hear from a Cairngorm 3/DDD expert how they would structure this.

Oh, so hey, what’s up with “net.flexpla.sharkys” anyway? Thanks for asking! I just registered “” for the heck of it (also, was just way too long), and am planning to host this “casino” at


January 28, 2011

The canonical Cairngorm 3 (among other frameworks) sample application appears to be insync by Christophe Coenraets. I say “canonical” because not only does Adobe use this as their model for explaining Cairngorm 3, but it’s also checked into the repository.

But nothing’s ever simple. When I try to build insync-basic from Christophe’s blog I get this error: “The children of Halo navigators must implement INavigatorContent”. And when I try to build insync-basic from Adobe’s SVN repository, I get this error “unable to open ‘\Observer\bin\Observer.swc'”.

Ah, life with open sores!

The problem with the insync-basic from Christophe’s blog would be easier to solve, but the version checked into SVN uses more current Cairngorm libraries, so I decided to attempt to fix that instead. This project referred to three missing SWCs: “Observer.swc”, “ObserverParsley.swc” and “Integration.swc”. I downloaded the latest versions from, added “observer-1.13.swc”, “observerParsley-1.13.swc” and “integration-0.15.swc” to the project’s lib folder, edited the project’s settings and removed the missing libraries from “Build path libraries”, discovered I really needed “integrationParsley-0.15.swc” so added that, and voila! it built without errors!

Feeling pretty smug, I clicked on “InsyncBasic.mxml”, pressed F11 to debug, selected Debug as Web Application and…nothing. Nada. Zero. No browser window opened, nothing appeared in the console, nothing at all apparently happened. Of course, I try this three more times, with no more luck.

But would Charlie Brown quit? Of course not. He’s going to keep on trying to kick that football no matter what. So channeling my hero, I created a brand-new Flex Project which I optimistically called “running-insync-basic” and copied everything in. And incredibly, in my new project, InsyncBasic.mxml launched!

The last step was to get InsyncBasicTestRunner.mxml to build. There were three steps to this:

  1. Adding “-includes asmock.integration.flexunit.ASMockClassRunner” to my project’s Additional compiler arguments.
  2. In Flex Build Path \ Source Path, adding the “test” folder (which is located in the project’s root at the same level as “src”)
  3. Getting mystifying build errors, looking for more Charlie Brown pictures, removing InsyncBasicTestRunner.mxml from my project and then adding it back. Boom, problem solved.

I also had to remind myself that, no matter how an experience like this makes me feel, I’m actually a highly competent software developer.

Okay, in the hopes that this might spare someone else the misery I just went through, here’s a project that builds. I didn’t write the code, only went through the steps listed above

Download a working insync-basic here.

The requirements of my app are simple. It needs to be beautifully coded per Cairngorm 3 standards, it needs to support deep linking, it needs to support localization and unit testing. It does not need to be in any way useful.

What it will be is a simple online casino with two games: Guess a number from 1 to 10, and Flip a coin. The odds are stacked against you, but you get $1000 virtual dollars for free just by signing up. Nothing will be charged to any credit card, and there’s no way to actually withdraw money. It is idiotic  by design, but it should do the trick. Here’s my quick and dirty wireframe which I’ll be basing the application on:


The next step is to translate this into a code architecture. First off, a Cairngorm 3 application has four Architectural Layers:

  • Presentation – presents data to the user and gathers input. i.e. the fancy UI
  • Application – performs the operations of the application. i.e. saving a form
  • Domain – models the business concerns of the application. i.e. the form data
  • Infrastructure – coordinates objects and integrates with other systems. i.e. talking to the server

I’ll start by mirroring the insync-basic structure and create my “sharkys_casino” project like so:

Next up, I’m going to try to figure out my classes, and see if I can’t apply this document to my design.

Applying the Presentation Model: Componentized vs. Hierarchical

But that’s enough for one night…

Design Driven Development

January 19, 2011

If there’s one step in the software development cycle that’s doesn’t get enough respect IMO, it’s the design phase. I’m not sure why that is. Perhaps it’s that programmers are expensive, and management would rather have them code than cooling their jets. Maybe it’s that specifications are hard to read and wireframe UIs are ugly and it’s hard to imagine how they’d look with nice art. Everyone’s busy. We’ll figure it out as we go…

Test driven development promises to cut development time by finding bugs earlier, but I believe it can actually generate more work if the fundamental design was wrong, as both the tests and the code being tested may now need to be rewritten.

The software development model I’ve seen work best is something like:

  1. Identify the people who will define the project (not always as easy as it sounds).
  2. Brainstorm with those people.
  3. Write up requirements: what the program will and won’t do, what platforms it will run on, et cetera. If there will be different users with different needs, identify those users and come up with scenarios for each. Return to brainstorming as necessary.
  4. Develop wireframes showing the various screens and how you get from one to the next. Prototype as much as possible. Work out as many kinks as possible before beginning to write code.
  5. Design code/data architecture and identify what frameworks and libraries you’ll be using.

And now, let the wild rumpus start!

Of course, this is no silver bullet either. You’ll get three months in and find a major new customer has become interested in the program, but they need some features to work differently. Or a new device hits the market and you have to make it work with that. Or some assumptions just turned out to be wrong. Or maybe, just maybe, you’ll find yourself ahead of schedule because you planned so well (this does happen!) and you’ll have time to implement some new features. Just spend the time to design them first.

Sort of kinda on/slightly off topic, but hilarious none the less:

Why you don’t like changes to your design