10 Tips For Working With Cairngorm

These apply to Flex 2.0.1 with any version of Cairngorm. Since people’s programming background varies in Flex, these are not facts, just my opinions based on my experiences using ARP & Cairngorm for over 2 years. Furthermore, there are alternatives to Cairngorm, I just cannot try them as much as I like. Now that I’m doing product work, I can’t just “try this framework on this new project”. I live in the same code base longer supporting existing clients, and can’t do dramatic re-factoring without getting fired.

1. If Cairngorm looks complicated, don’t worry, it is, and you’re not alone

“Bunch of code on _root vs. all of these classes and conventions? This’ll take forever!”. It takes getting used to. I felt “comfortable with Cairngorm” on my 4th project with it. To this day, I still mod it though, and try different things. As more people come into Flex, there are more cool ideas and techniques floating around.

2. If it feels like it’s taking a long time just to do something in Cairngorm, it does.

“OMFG… 3 classes just to execute what would take me 1 line in Flash? Lamesauce!”. Code gen can help here, at least at the beginning of the project.

3. Only Commands set data on the Model; you can break this, just don’t if you can help it.

In Model View Controller, only the Controller sets data on the Model. In this case, the Commands are the Controller (usually), and as such, setting ModelLocator data is their job, and their job alone. If data is getting f’d up, you immediately know it’s in the Command. You never have to question “who’s setting my data, where, and when?”.

4. Delegates make the server call and parse the data (sometimes in a Factory)

This has only happened once in my career: I was hitting PHP for the back-end, parsing XML, and in the middle of the project, we switched to OpenAMF and Java where I had to parse objects. Using Delegates means you only have to re-code your Delegates, not the rest of your app. The Commands still get the same data.

The only reason I use Factories is because A) parsing can be a lot of code and you don’t want to make your Delegates look more complicated than they are and B) you can share parsing routines easily in the same Factory class.

5. If you see a Command parsing data, it’s coded wrong.

Parsing is differently from filtering, modifying, and assembling. IE, making Value Objects from XML should be done in the Delegate, not the Command. Making associations between ArrayCollections, injecting default values are both ok. Remember, the key here is if the Command is touching raw server data, you’re either not using Delegates correctly, or have AMFPHP/FDS/WebOrb working correctly, hehe.

6. There are 3 ways to use Commands & Delegates. I prefer A because it’s consistent, leads to short class files, and is very explicit.

A) For every use case, you make 1 Command and 1 Event. This can sometimes also mean 1 Delegate. (ie, LoginEvent, LoginCommand, LoginDelegate)

B) For every use case that’s related, you can consolidate them into a package path. So, Login, ChangePassword, and ForgotPassword would all be in the same class. You’d then use constants to determine which one to run. (ie, LoginEvent has LOGIN, CHANGE_PASSWORD, and FORGOT_PASSWORD as String constants. Your LoginCommand has a switch statement which determines which one to run. Your LoginDelegate has 3 methods; login, changePassword, and forgotPassword that your Command can use.

C) Variances on B. Maybe 1 Event and 1 Command, but multiple Delegates. This is not a cop-out bullet item, rather, I’ve seem many derivatives that can all be traced back to “B with mods”.

7. ViewLocators are considered bad practice.

That said, there are developers who still love and use them. The use case, however, is valid: Having a View “know” when something in a Command has occurred. I use callbacks, some set data on the Model to trigger callbacks on the Views (maybe via a setter function), and some use addEventListener in tandem with CairngormEventDispatcher.

8. ViewHelpers are considered bad practice.

That said, there are developers who love the idea of “code behind”. I’ve yet to see a consistent theme on the blogs and mailing lists. There are 2 reasons that are common:

A) They don’t like mixing ActionScript & MXML.

B) They want to separate their View’s from their “View controller code”

Some use the script tag to point to an external file (lame in my opinion; you have to define your controls as member variables and you end up with twice as many View classes). Some use inheritance where you extend your GUI MXML. Others take the reverse, and have the GUI MXML extend the ActionScript ViewHelper. Some will even take the Composition over extending MovieClip approach I’ve seen a lot of coders do in Flash. Instead of their ViewHelper extending a view class, it’ll instead take a UIComponent as a parameter, say in an init method, and use that UIComponent via composition.

To me, you’ll get over it as you get more comfortable with Flex. Code your components in MXML with code up top in a script tag. If you really need efficiency, or start doing some really low-level, abstract type classes, then you can start coding your components in ActionScript. If you want to get stuff done today, use MXML.

9. Don’t use flash.net.Responder, use mx.rpc.Responder instead.

Yes, it’s frustrating because Flex 2.0.1 doesn’t give you the source, but in my opinion, Flex Builder doesn’t handle same-named classes very well. Just go with what Flex uses, and call it a day. If someone requires flash.net.Responder, code a wrapper to bring him into Flex land. “Sir… you need a tie to get into this restaurant. We have one in the back, one moment.”

10.Try not to have View’s use CairngormEventDispatcher (or Events that extend CairngormEvent use event.disaptch()).

Instead, have those deeply nested views dispatch events. Either bubble them up so a master controller View can then fire off Cairngorm events, or bucket-brigade them up. The most common scenario is itemRenderers that are a custom class in DataGrids.


– make the itemRenderer class. If you have something in it that is clickable, dispatch a custom click event. Make it bubble.

– extend the DataGrid that uses your custom itemRenderer, and put the custom event in the metadata up top. Otherwise, the class that houses the DataGrid will only be allowed to subscribe to the event via MXML, only ActionScript. If you use MXML, it’ll fail to compile because the DataGrid doesn’t have that event in it’s source code.

It may feel cool at first to have a LoginForm for example dispatch the LoginEvent, but if you need to use it for a different purpose elsewhere, you’re screwed; it’s hard-coded to use a specific CairngormEvent. This applies to all components. Encapsulate your components and do your best to do what BT does: “bubble it up”.

29 Replies to “10 Tips For Working With Cairngorm”

  1. “5. If you see a Command parsing data, it’s coded wrong.”

    Can you elaborate on why its “wrong” to have the commands parse the data in their result handler ( say for e.g using a common xml utility class that can parse the data )

  2. Read the comment you mention. Still not sure why its wrong.

    If I understand you correctly, the “litmus test” is that if the data from the middle-tier changes, then the impact on the client-side code should be minimal. Consider code something like the below in the onResult handler of a command

    var books:BookCollection = DataParser.getBooks(data);
    ModelLocator.books = books

    When data changes, the only impact is to the DataParser class, which should satisfy the mitmus test you mention.

  3. If you end up doing a project, and your Delegates and Commands never get more complicated than 2 lines of code, you should start questioning if Cairngorm is overkill for what you need. Seriously, most of my projects start with the 2 lines of code you have above, but as the weeks and months wear on, the parsing and data managing starts to grow in scope, well beyond 2 lines of code.

  4. “3. Only Commands set data on the Model; you can break this, just don’t if you can help it.”

    I like this idea, but it’s new to me. Should it be obvious?
    When I’m using a model value to change a viewstate, I often change that all over the place. Should I create events / commands for such an action?

    “4. Delegates make the server call and parse the data (sometimes in a Factory)”

    “5. If you see a Command parsing data, it’s coded wrong.”

    If you are using the command as a responder, then the ‘result’ method in the command be doing the
    data parsing, right? Or am I misunderstanding something?

    I am building an AIR application. The client wants to keep the option open to move it to the web. I set up a Flex Library project and an AIR application that uses the Flex project.

    The delegate code to load the XML file is AIR specific, since it is loading a file. It is in the AIR project.

    The code to process the XML is not AIR specific, and is located in the command which is in the Library.

    I seems like in this case, I would not want to parse the data in the delegate.

  5. Commands being the Controller, and the C that’s in the MVC setting data on the Model. For example, Flash Player 6 implemented _global. This allowed an easier way to implement global variables, much like Director had for awhile. Not matter where you were in your code, not matter the scope, you could access a global variable. This made it an ideal place to access important data anywhere.

    The downside to global variables is that everyone has free for all access to it and can change it however they wish. Others who are accessing it are not aware of those other bits of code doing modifications, and sometimes their expectations are wrong. This leads to challenging debugging situations where your data is getting set and “you just don’t know where”. Very frustrating, and time consuming to debug. You have to look all over your code base just to find 1 set, and then determine if that variable being set is the actual cause of your problem.

    Using the Controller in MVC allows strict access to setting data. First, you know exactly who is setting your data; the Controller. There is no hunting in code, no guessing, you just immediately know if you follow the convention. Second, it focuses your debugging, making it quicker and faster to find the offending code. Part of the Command paradigm in Cairngorm is sequester the Controller setting data on the Model to be strictly in the realm of Command classes, and Command classes only. Since Flex has a wonderful binding mechnism (caveat: challenging to debug the binding chain), this means that even though Commands are the only classes that should be setting data on the Model, View’s and others can still be notified of those changes via the Bindings. This allows controlled data setting, with the View’s updating to show the data they need to know about; everyone’s happy.

    …usually. Sometimes there are just use cases where it gets pretty ridicolous. Like, if I have a Name popup editor that changes your username, do I really need to make a use case for “Changing your name?”. I mean, dude, it’s 1 line of code, Model.instance.name = newName_ti.text.

    In Cairngorm? NOoooooooo…. you have to make event, command, and maybe delegate. Bloody hell. However, if you don’t, you’ve broken the rules, and suddenly someday in the future, you’ll be wondering why your username is getting changed. Or will you? I mean, it’s pretty obvious your using a dialogue, right? That to me is a valid breaking of the rules for deadline purposes. The second that dialogue starts doing stuff without user ineraction, though, is when things start getting dangerous.

    Other people use state information on the Model. I can understand this. They’ll even use setter functions to have magic happen when their bindings fire. As long as you make a seperate Model class for this, seems ok to me. That way, you know that “Only Commands can set data on the Model, but anyone can set data on the StateModel”.

    Regarding your Delegate example, 2 questions. First, does your Command get the same type of data? If yes, then you should just change your Delegate to point from the AIR XML to another XML. That way, the rest of your application remains unchanged. For example, if you have 2 HTTPServices to get the XML, you could change 1 line of code in your Delegate; just get the service from the ServiceLocator. 1 points to the AIR stuff, another to the non-AIR stuff.

    If your Command accepts different data, that’s different. Then the Delegate thing above makes no sense; it’s different data.

    Bottom line, if your XML parsing code is not AIR specific, that should be in a Factory (doesn’t have to be). That way, that Factory class can be shared. Delegates do not “point to data”; those pointers are defined in the Services.mxml. So, technically, you should only be changing 1 line of code in your Flex app to switch it to the web: the URL to the XML in the Services.mxml. Make sense?

  6. Jesse, I think there’s a third option in point 8 that you don’t mention but is very useful for more complicated views. It’s not code-behind as you’re not creating a new class, but really just taking the code from the Script block, putting it in an external file, and linking to this file with a Script tag. It’s functionally equivalent to using a Script block as you don’t have to define your controls as member variables. You do have the disadvantage of doubling the number of files so it’s only worthwhile if your the Script block grows beyond a certain point. However in these cases, the inconvenience of an extra file is more than made up for by the increased usefulness of the Outline tab in Eclipse. It’s useless for Script blocks in MXML files but in a pure AS file, it lists all your variables and functions so that you can see all of them at a glance and click on them to move quickly to the desired point in your code. I agree with you that the Flex version of code-behind is a waste of time. I remember reading a post by Tink(?) ages ago recommending the approach outlined above over code-behind. There was a lot of dissenting comments at the time but I think he was on the money.

  7. Hey Jesse, Thanks for opening an interesting article. It’s great to read a different perspective on things.

    In 7. you write “I use callbacks,…” could you elaborate on how you implement this? Are your coupling a callback function in a view to the event, received by the command to do this?

    In regard to 8. I also think that it is valid to have a “helper” class. I prefer to call it what I think it is: a “controller”. By that I think of the conceptual controller of Cairngorm and MVC as a composite of various parts; FrontController, Command’s and the more local controller (helpers). The key motivation points for me in the use of these view-specific controllers are;
    #1: Working closely with a UIX designer, makes the flow tighter with controller (again, I see this code as the controlling part of the view) and view separated, giving the designer only the MXML/View to work with, and the developer the controller (or “helper”) part of the view.

    #2: Now that the part of the conceptual controller in the MVC, that updates the Model, has be specified to only reside in the Commands, which are loosely coupled to everything, and only runs and terminates as an executed process, I see an even better and more needed use of the actual View specific Controller that lives along with the View. This Controller have a high coherence (in regard to the View it acts as controlling unit for) and would decouple the View even further from say implementations of system events etc. (cairngorm events) as you also motivate in part 10.

    3# Higher reuse of controller code. As view and controller (helper…what ever we call it) is separated the reuse (our experience) grows.

    Again thanks for an interesting article!

  8. Pingback: anil4it
  9. Pingback: Anilkumar
  10. There is this debate about ViewHelper/ViewLocator people promoting it not to be used.

    In some cases a view can send a responder attached to an event thus being aware and reacting at data changes directly.

    But what to do when there is something like a flash media server netconnection object that has a remote method, invoked by the server that would need to trigger changes in a view.

    What to do in this case ?

Comments are closed.