From Day 1 I hated how Cairngorm Commands / Delegates didn’t give a status to what they were doing. Since Flex‘ primary purpose is a Rich GUI, and there isn’t a built in way to get status on Commands. For example, the flash.net.FileReference object will give you a progress event. This gives you the ability to show the actual progress of the upload in a progress bar. While most Commands are simple request / responses, sometimes you’ll call many of these in a row, with different ones at different times in the case of editing wizards.
Even more important, however, is the flow of this logic. Some Commands contain logic that can be re-used elsewhere. For example, a GetPerson Command that get’s a specific person from a database by ID. There can be many other scenarios where you need to get a specific person from the database where you wish to store a local reference to it (for an EditPerson form for example), or you are just querying the data for some other operation. This still poses a problem for other Commands, however. They can’t re-use the Command in the Cairngorm way, but rather the Delegate way. Meaning, a Delegate usually takes in an mx.rpc.Responder. Therefore, you can call a method on a Delegate, and get a useful response in a result handler when it’s done, and an error response in a fault handler. You can’t do that with Commands. Commands are run only by the Controller, and have no callback support built in.
While a Delegate, assuming one exists for the specific Command in the first place, is a viable way of re-using functionality, the application logic usually happens in the Commands, not the Delegates. The Delegates are responsible for merely getting the data, and parsing for use by the application. The Commands are the ones who do useful stuff with it like stick on the ModelLocator, or update your data model as appropriate. That valuable, and specific application logic is what I’m talking about here. Written in an encapsulated form, it is ripe for re-use. Yet, you can’t.
Therefore, the only official way of sequencing Commands is using the SequenceCommand which basically locks you into a specific order, puts too much knowledge into a Command, and risks making them state-full. Meaning, by default you are locked to a specific order; the order in which you coded the Commands to call each other. The potential exists for a Command to “know” it was called by something else, thus forming a potential dependency. Dependencies bad. Third, if you know this, you may be tempted to put some conditional logic in there to help adjust for this and say “If I was called by the GetPerson Command, then I need to do this… otherwise, I’ll just do this.” Commands are use cases, and shouldn’t be determining the “way” they run the use case. If I ask you to SaveTheData, just save it. The Event that gets passed into the execute function tells the Command all it needs to know. While some would argue that the alternative Cairngorm where you have Many Events for every 1 Command as opposed to the default which is 1 to 1 allows this scenario to work well. While very true, it doesn’t scale well. Meaning, while having 1 LoginCommand capable of doing the work for a LoginEvent, ForgotPasswordEvent and ChangePassword event is very possible just by adding a switch statement for the event’s type in the execute function, your classes get very big, and less flexible. Yes, you do end up with more classes, but that’s what folders are for. Furthermore, there is nothing wrong with a bunch of classes that have less than 100 lines in them. Compare this with a few classes that have a thousand each. This is why a lot of people like Ruby on Rails; does a lot with few lines of code.
Remember, we’re running client code here, not server-side. Our scalability needs are for code maintenance not performance. So, in this case, less code is better regardless of the performance implications.
Even worse, you run into scenarios with the above where you have the urge to make your Commands state-full, meaning, they “remember” their state. That further makes your Commands less re-usable. Now to use a Command, you as the invoker have to know how the Command will use the Event class you choose, who it may call next, and what state it may already have. As if programming wasn’t hard enough. You shouldn’t have to know all of that stuff. Just dispatch an event, and have faith your use case will get resolved.
How to solve these issues? If you were using Joe’s Controller, you could just add an event listener, make your call, and get an event when it was done for the asynchronous operations. For the synchronous ones, you could just return a result. Taken a step further, you could also return a token instead. For example, if the Controller were just an instance, the event model would work well. As soon as you handled the the event, the Controller instance would go out of scope, and the Garbage Collector in Flash Player would clean it up. However, Controllers are Singletons, so that won’t work. This means the user of the Controller is now responsible to “remember” to do a removeEventListener to ensure it doesn’t get events later it doesn’t care about. Kind of like the space shuttle docking with the space station. When it’s done, it first un-docks. That’s lame, though. It makes it a pain to deal with.
The third option is to do what HTTPService and friends do using the token pattern. Since HTTPServices can either be used as 1 time instances or act like a Singleton (only 1 instance instantiated 1 time in the Services.mxml), it needs to support both ways of working. As such, all calls create their own instances of the call and return it. In this case, they’ll make a call, and associate a token with it. They’ll return this token to the caller. When the call comes back from the server, the HTTPService knows which token it is for, and so does the one who called it since he has a unique token for it. You can treat these tokens as instances. The only minor downside to this is when you are using these classes like HTTPService as instances, it takes a few more lines of code just to make a call. This is because it is assumed you’ll usually be using only 1 instance, but the class creators don’t want to lock you into an implementation, so give you the option to do both. Bottom line, the Token pattern is really for the developer to be able to tell the difference between multiple calls to the same service by comparing the token you get when making the call to the token you receive from the result handler’s event.
…in Cairngorm’s case, he doesn’t have that option. You dispatch an event and that’s the last you hear of the call. Years ago, the suggestion was to simply set a ModelLocator variable as a state variable, and change it’s value when the Command was done. The first problem with this is that it only works if you only ever call the Command once. Since Commands are created as stateless instances, you could have a scenario where many are running. One variable cannot work for keeping state of all Commands. Secondly, this doesn’t scale because you then have state variables. View’s in Flex 2 have a great way of representing their own state and don’t need to offload that baggage to the Model. While the View can react to a change in the Model such as databinding, for GUI development, you need more than just a global variable. You need callback support.
I developed some extensions to Cairngorm to support this as have others. Grant Davies and I originally did this for back in the Flash days, but with a different approach. We removed the need for Events, and just gave Controller the ability to launch Commands via method calls. We’d pass in parameters with the first 3 being scope, result callback function, and fault callback function. This allows any View, anywhere, to launch a use case AND have a result callback when the Command is done. Cairngorm & default ARP can only do the first part, not the latter.
This changes the game, though for a lot of people’s perceptions. This means that the View in some cases is acting like a Controller. This is hard for a lot of traditional, non-Flex / Flash devs to understand. Traditionally non-GUI code handles this. However, a lot of people just assume that in Cairngorm’s case this means the Commands which leads to some of the problems mentioned above. This lead to the use of ViewLocator, a Singleton class that can access any View that has registered itself via a String. This allowed Commands the “formal” ability to access a View’s methods whenever it felt the need. The only justification I’ve have for this disgusting class was in a discussion over IM with Spike Milligan. It is in the case of a base Delegate detecting an expiring of a user’s login. You need some way to make the whoever your main view is to spawn a Login View in a PopUpManager. Another way is to have your main view add an event listener to the CairngormEventDispatcher for a “PromptLoginEvent”.
A lot of Views in Flex case aren’t really View’s at all. SystemManager for example merely manages how the application is setup to actually show Views. Application.mxml is the main View, but typically he only has 2 children, the CSS style sheet you are linking in and Darron Schall‘s “MainView”… aka, your app.
Even more granular, now that event bubbling is built into the Flash Player, we can encourage the “higher views have higher concerns” paradigm. Meaning, the higher the View is in the DisplayList, the more important it is. For example, Application.mxml is pretty damn important. Without him, you have no Flex app. MainView is the 2nd most important; he instantiates Cairngorm and starts your main application up. Without him, you just see the loading bar and resulting blue gradient. In an EditPersonWizard, he manages child views which in turn manage specific Person properties. An important key here to the whole thing is that they listen to their parent. If the parent, the EditPersonWizard, says next step, they disappear. The parent manages the children in the wizard, sets their data, and keeps a track of their changes. When the choreography is done, you’ve “Edited your person using the Edit Person Wizard successfully. Have a nice day!”. In effect, the EditPersonWizard is a controller. The same can be said for MainView. The same can be said for Application. They don’t just instantiate Views; they control them.
One thing you should strive for is to NOT put Cairngorm specific event dispatching in your View’s. You should treat them as encapsulated components that you can reuse. Rule of thumb: If you can put a Cairngorm event to be dispatched in a parent instead of the current View, do it. With Flex 2, it is now easier to do this by either dispatching an even up to the parent, or just bubbling it up even higher than that. You should define the events in the MXML metadata, since a parent should know which events its children will dispatch, even if it won’t actually use them. This is very valid, btw; I don’t use a Button’s mouseDown or render event, but I commonly use its click event. Either way, all 3 are strongly-typed. You should make your Views strongly typed as well, even with the events.
In effect, this allows your child views to dispatch events up the DisplayList and those higher up the chain who need to know get what the need to know. For example, a Button inside Step3 inside of EditPersonWizard doesn’t need to be reporting that the user clicked him to MainView.mxml. Step3 knows how to manage his subordinates and take the appropriate action. He’ll inform his parent, EditPersonWizard, of any changes that are important.
What if Step3 needs to get a person from the database, however? Could you not just put a Cairngorm event dispatch right there in Step3? Of course! If you are in a hurry, go for it. Deadlines are deadlines. Should you? No. You couldn’t re-use this View elsewhere without dragging all of your Cairngorm code with it to work. Instead, you could build in a setter for the EditPersonWizard that was specifically put in place some MainView could then set it. But how does MainView.mxml know when to get the person? Does it need it immediately, or is it optional? In this case, we’ll Delegate the responsibility to Step3. Support is built into EditPersonWizard, but nothing is implied or demanded. Step3, when needed, can bubble the event up. EditPersonWizard can then do absolutely nothing as the event passes by. MainView can then catch this event (it’s defined in the EditPersonWizard’s metadata tag remember, so we have strong-typing in MXML here), and do the normal Cairngorm getting of data routine. Even without callback support, the data is set on the ModelLocator via the Command, and since it’ll probably be bound in MainView like
You can see if you build View’s this way 4 things happen, 2 of which are good. First, you’re views are re-usable since they don’t have Cairngorm dependencies. So, you can re-use in the same application even with different data. Second, you don’t have to bind a lot of View’s to ModelLocator. Instead, they are given their data to them by their parents, again making your View’s more flexible. Third, you write more code in your View’s to support data in children. While this is more code, it’s good code in my view. Still, more code isn’t necessarily good, but better more code for the sake of encapsulation. Fourth, your higher level views spend a LOT of time getting data for people. If this is MainView.mxml for example, who has very little Views to handle, this is a great thing. For one thing, ALL Cairngorm use cases are dispatch from (hopefully, not always the case) 1 spot. Just like Commands are great in that you know for a fact they are usually the ONLY ones who set data on ModelLocator, you can be sure that the only one handling main application control logic is in MainView.
The downside is this can be a lot of code, even for smaller apps. This is why a lot of programmers feel they need to put this stuff in Commands since at first glance, they appear related. They aren’t, though. The View’s are dictating what data they need since they are best suited at this. Things like lazy loading happen at the View’s discretion for example vs. the Controller. Further, the Views are the ones passing data up, whether packaged in an event object, or exposed view public getters. The parents of those Views as well as MainView may have context about that data that Commands may not know. In effect, you shielded the Commands from all of that View logic… thus reducing their code size. That’s a good thing! Views should be managing Views. Views can act like Controllers for other Views. That’s just the nature of GUI development whether composition or inheritance.
The fatal flaw in this scenario is that MainView is crippled in this scenario in getting back to the View’s with their needed data or progress events. If you ask for time off from your manager, but their boss never responds to emails, you’ll never know if you can take those days off you need. This is the main problem I had with ARP, and the same problem I have with Cairngorm. With Cairngorm, I modified CairngormEvents to store callback functions. “Call this when you’re done”. This callback is then called from the Command “when it’s done”. This could be immediatley or after a Delegate returns from the server… whatever, whenever. Bottom line, a View can get a response when a use case is done. In this case, MainView can then pass the data down to EditPersonWizard, who will then pass it to Step3. If the Command just set it on ModelLocator, MainView doesn’t have to do anything in this case. But, if you were saving your changes, for example, and EditPersonWizard was disabled while the save happens, MainView can enable the form again once the save has successfully completed.
In effect, this makes MainView a very effective View controller. For scalability purposes, you make a few MainViews who manage their section of the app.
One of these days I’ll explain the technicalities behind using Callbacks; strongly typed responses that Delegates return to Commands, who in turn can return to Views. Views can use them just like they use ValueObjects, and get only the info that a Command allows it to have. ResultEvent is too generic, not strongly-typed, and View’s have no clue what they are supposed to do with it. Furthermore, it’s a code dependency risk too. That’s another blog entry…
11 Replies to “Cairngorm Command Flaws and What You Can Do About Them”
I use a custom event wich is base of the Cairngorm evet which has 2 properties re:ResultEvent,fe:FaultEvent and also implement a interface which I call the IEventResponder. This interface has 2 functions handleResult and handleFault which are supose to clone the event and redispatch it thru the CairngormEventDispatcher. Now on my commands when I receive a response from the server and I want to notify view’s of it I call handleResult function off my event which will dispatch to the CairngormDispatcher. So if I want to listen to a result from a view I would just register a listener into the CairngormEventDispatcher and handle the result. Hope this makes sense!
Is MainView anything other than the idea of wrapping your whole UI in a root Canvas or something? I’ve never heard of it and can’t find any substantial reference to it in the Google.
Omar in the house.
Yeah dude, that makes sense. I’ve seen some poeple post about adding event listeners to CarigngormEventDispatcher so that anyone can listen to any Command’s thats fired.
Typically, though, I view Commands as encapsulated method calls strictly in the Controller. With that said, I think it’s fair to know when a SPECIFIC call is done, not just any call, and more specifically the call that the View made. While Commands don’t support the token pattern, and most View’s only make a single request, I’d still like to have a Command tell me when it’s done TO the View that made it. Then again, if I don’t know WHAT specific request, I guess it’s stateless, therefore using an addEventListener could work. Bottom line, I View Commands as just glorified methods and a callback as a way to return a result. Dispacthing events just seems… weird. :: shrugs :: Next project, I’ll give it a whirl.
Yeah B, you just basically put everything in there (Cairngorm Controller + Service Locator + Your main app code), excluding the CSS file.
It’s kind of like when you would make a main MovieClip in Flash, and just attach that to _root.
I add specific listeners to the CairngormEventDispatcher to listen to results event’s and fault event’s off the command not to listen to any command fired. So if I invoke a command GetUserInfo I would add the following line to listen from the view when the request is received,
If I don’t need to notify the view in any way then I do a regular command and don’t add any extra code.
Hey Jess… do you have a quick sample app with the modified framework? It might help us understand what you’re trying to explain.
Great Article. Can’t say that I haven’t had similar problems. I greatly dislike observing the model to see what my commands are doing… sometimes that works but it’s not my preference. I also bubble up from components to app specific views and then dispatch my CG Events from there. One approach I have been using for a while and it works fine in situations where only the calling view and/or it’s children need to know about command status, is to have my views implement an interface, say IVIew, and then pass a reference to the view with my Event. Command checks if the event.token.originatingView is IView and if so calls update(originalEvent, resultEvent). In the update I can then use a switch statement to react to only originalEvent.types that I select.
In situations where multiple lateral views might need updates, i’ve been playing with a generic CommandEvent that all Commands trigger. The type of the original event that triggered the Command is used by Views to filter out events they arent interested in. It works but I fear won’t be very scalable.
love your work,
quick couple of questions, the events you launch from the children how do you type them? that is to say do you create events that are Cairngorm events, but dispatch them as normal flex events using dispatchEvent(myCairngormEvent) and then when you arrive at the appropriate parent re dispatch them as cairngorm events myCairngormEvent.dispatch(), or do you do it some other way? If they are not cairngorm events how do you pass data up the views?
Second I have created individual models for any parent view that is significant, i.e. has several children that have no model and do NOT dispatch cairngorm events, these intermediate parent views also belong to another view (lets call him the super parent). I have been dispatching Cairngorm events from these intermediate parent views that effect their particular model and also dispatching normal events up to their super parents for events that effect them, the super parent then calls its specific cairngorm events as required, is this ok?
Did you ever reply to David’s last thread? I was also curious about the data typing of the events that you passed up to parent views. Thanks for a great post!
I absolutely agree with Jess. There is a small trick which can enable us to break the shackles of command logic. By using viewcontroller..
an implementation of the same is available at
I’m reviving an old thread here to get your current thoughts on how to handle the issue of notifying a view when a Command has executed and returns its OnResult/OnFault so that further logic can be executed…
As I understand it Cairngorm 3 proposes extrapolating all methods of a view into it’s own model (singleton) which you can then call from the Command/Responder’s Result/Fault handlers.
While I haven’t attempted to use the beta yet, this seems like a lot of remodelling is required!
Do you have any update on how you’ve solved this problem since 2007?
Comments are closed.