Patterns of GUI Architecture in Cairngorm and PureMVC

In the flex application we are currently developing, the need has arisen to get some more structure on the code. In the upcoming months, we are going to do a great deal of flex development, heavily expanding the functionality of the application, and of course we want to keep a maintainable application. Because of this, we are in the need of some structure and guidance on the architecture, hence the need for an architectural flex framework and some good patterns to follow.

In this post, I will discuss a specific area of the two current major architectural frameworks in flex, PureMVC and Cairngorm, namely how they apply patterns of GUI architecture.

What are Patterns of GUI Architecture?

As I previously wrote about in my post When Thin Clients Grow Fat, developing flex applications quickly reveal the need for the same kind of architectural guidance as when developing real, native, fat clients in frameworks like Swing and .Net Forms. To help architect such applications, some patterns on GUI architecture has been developed and described. Martin Fowler has some good descriptions of some of the more know, like Presentation Model and Supervising Presenter. These are not whole UI architectures like MVC, but smaller parts of architectural guidance, related to how the logic of the application relates to the api of the view framework.

How PureMVC Applies UI Patterns

PureMVC has a construct called a Mediator, which is just what it sounds like, an application of the Mediator pattern, to mediate bewteen the apis of the view and the apis of the rest of the application. This is a key construct, in how PureMVC implements the View-part of the MVC architecture, and is introduced to reduce the dependencies between the application and the view, hereby lowering the coupling in the entire system.

The PureMVC Framework Overview documentation has the following to say about mediators:

Mediators help us to create or reuse existing user interface components without the need to imbue them with knowledge about the PureMVC application they communicate with.

… View Components display data or accept user gestures. In a Flash-based application, they typically communicate with their Mediators using Events and exposing some properties for the concrete Mediator to inspect or manage. A Mediator connects a View Component with its data and communicates with the rest of the system on its behalf.

This, actually is not a very precise description of how to use a mediator in PureMVC. Luckily, PureMVC has an Implementation Idioms and Best Practices document, which lists an actual example, the LoginPanel example. In the example it shows, that only the mediator knows about the view, and that the view does not know about the mediator. Here is a source extract of the PureMVC documentation:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" title="Login" status="{loginStatus}">
  <mx:MetaData>
    [Event('tryLogin')];
  </mx:MetaData>
  <mx:Script><![CDATA[
    import com.me.myapp.model.vo.LoginVO;

    [Bindable] public var loginVO:LoginVO = new LoginVO();
    [Bindable] public var loginStatus:String = NOT_LOGGED_IN;

    public static const TRY_LOGIN:String = 'tryLogin';
    public static const LOGGED_IN:String = 'Logged In';
    public static const NOT_LOGGED_IN:String = 'Enter Credentials';
  ]]></mx:Script>

  <mx:Binding source="username.text" destination="loginVO.username"/>
  <mx:Binding source="password.text" destination="loginVO.password"/>

  <mx:Form id="loginForm">
    <mx:FormItem label="Username:">
      <mx:TextInput id="username" text="{loginVO.username}"/>
    </mx:FormItem>
    <mx:FormItem label="Password:">
      <mx:TextInput id="password" text="{loginVO.password}" displayAsPassword="true"/>
    </mx:FormItem>
    <mx:FormItem>
      <mx:Button label="Login" enabled="{loginStatus == NOT_LOGGED_IN}" click="dispatchEvent( new Event(TRY_LOGIN, true ));"/>
    </mx:FormItem>
  </mx:Form>
</mx:Panel>

and the class mediating this view component:

package com.me.myapp.view {

  import flash.events.Event;
  import org.puremvc.as3.interfaces.*;
  import org.puremvc.as3.patterns.mediator.Mediator;
  import com.me.myapp.model.LoginProxy;
  import com.me.myapp.model.vo.LoginVO;
  import com.me.myapp.ApplicationFacade;
  import com.me.myapp.view.components.LoginPanel;

  public class LoginPanelMediator extends Mediator implements IMediator {
    public static const NAME:String = 'LoginPanelMediator';

    public function LoginPanelMediator(viewComponent:LoginPanel) {
      super(NAME, viewComponent);
      LoginPanel.addEventListener(LoginPanel.TRY_LOGIN, onTryLogin);
    }

    override public function listNotificationInterests() : Array {
      return [ LoginProxy.LOGIN_FAILED, LoginProxy.LOGIN_SUCCESS ];
    }

    override public function handleNotification(note:INotification):void {
      switch (note.getName()) {
        case LoginProxy.LOGIN_FAILED:
          LoginPanel.loginVO = new LoginVO();
          loginPanel.loginStatus = LoginPanel.NOT_LOGGED_IN;
          break;
        case LoginProxy.LOGIN_SUCCESS:
          loginPanel.loginStatus = LoginPanel.LOGGED_IN;
          break;
      }
    }

    private function onTryLogin(event:Event) : void {
      sendNotification(ApplicationFacade.LOGIN, loginPanel.loginVO);
    }

    protected function get loginPanel() : LoginPanel {
      return viewComponent as LoginPanel;
    }
  }
}

This pattern is what is known as either a Supervising Presenter or a Passive View. These patterns both extract behaviour out of the view and into a presentation class coupled with the view. In addition, in both patterns, this is done in a “presenter knows the view, but the view does not know the presenter”-way. What separates these two patterns from each other is how much logic to extract. In the case of a Passive View, all logic possible is extracted from the view, putting all responsibility on the presenter to control and update the view. This allows for easier testing but also a lot more work on the presenter class.

So, which flavour is the mediator? In my opinion, the mediator comes closest to being a Supervising Presenter, at least if I look at the LoginPanel example. In that example, model instances are used in the view, and databinding is used (still within the view), to bind form fields into the model instance. In addition to this, the documentation for the puremvc mediator says:

A View Component should encapsulate as much of its own state and operation as possible, exposing a simple API of events, methods and properties.

The responsibilities for the Mediator are primarily handling Events dispatched from the View Component and relevant Notifications sent from the rest of the system.

This shows, that a mediator is supposed to put some burden on the view, while keeping itself lean.

How Cairngorm Applies UI Patterns

Cairngorm has no notion of a mediator, a supervising presenter, passive view or anything like it. Actually, it has been bashed upon by many, as it advocates a solution of simply data-binding of view component state directly up into the model. And to make matters worse, the model is simply a global state, expressed through a singleton.

Looking at the Cairngorm documentation and the examples (both the introductory contact management app and the “advanced” Cairngorm Store), only make this stand out even more clear. The views have lots of logic, and as such operates as what is known as the Autonomous View pattern. So, what is an autonomous view? Martin Fowler describes it as:

Puts all presentation state and behavior for a window in a single class.

which to me is a bit like having a no pattern pattern. Simply chunk everything together. This, combined with the fact, that the autonomous views in a Cairngorm based application are advocated to databind directly into one global model instance, makes for really bad separation of concerns between the view and the model.

Even though I think that most of us can agree on the above being a really bad solution, it does not make all of Cairngorm bad. You “just” have to know this up front, and do some extra work yourself. One way to solve this in Cairngorm, is to introduce your own presentation class, separating the view better from the model. In addition to this, you get the option of choosing something else, than a supervising presenter as PureMVC advocates. But, you are ending up coding something to fix a mischild of Cairngorm, something that is already build into PureMVC. In addition to this, if you do not want to databind directly into the model, you will have to think of a way to get databound data from the presenter back into the real model.

Conclusion

So is PureMVC better then? This is a question, that cannot be answered by this post alone. The UI patterns is just one part of both frameworks, albeit an important one. One could argue, that you get more out-of-the-box with PureMVC, the mediators being a builtin concept of the framework. The mediators and the communication from and to mediators through notifications, have been nicely worked into the PureMVC framework.

Further Reading

If you found this article interesting and want to know more, I recommend looking at these resources:

June 9, 2008 · polesen · 19 Comments
Tags: , , , ,  · Posted in: Design, Rich Internet Applications

19 Responses

  1. Steven Webster - June 9, 2008

    So CairngormStore is intended as a very simple example of using Cairngorm, it’s not the approach advocated for all applications. Cairngorm isn’t prescriptive about the view, it simply recommends that you leverage data-binding to bind data between model and view.

    Please see Paul Williams blog for excellent descriptions of many of Fowler’s patterns implemented in Flex, and leveraged or leveragable in your Cairngorm applications – http://weblogs.macromedia.com/paulw

    Cairngorm does not advocate “chucking everything together” into a single class, and would only advocate that if that was the simplest thing that worked forthe scale of your application. i wouldn’t represent this as a a “michild of Cairngorm” , but rather that we’ve from the outset stated that Cairngorm is not prescribing the implementation of the view.

    Because Cairngorm is a framework for Flex primarily, we defer to data-binding as the way of binding between a model and view, and the implementation of the model and view are both developer decisions; we only advocate the ModelLocator as the singleton through which you can locate *all* of your models.

  2. polesen - June 10, 2008

    @Steven:

    When you say:

    CairngormStore is intended as a very simple example of using Cairngorm, it’s not the approach advocated for all applications. Cairngorm isn’t prescriptive about the view, it simply recommends that you leverage data-binding to bind data between model and view…

    I could say “ooh, okay”, but in my opinion, documentatation and examples therein are key to a framework, as they communicate the intent of the framework and the parts of it. One part being the view, of course.

    The Cairngorm Store application on cairngormdocs.org is listed as the “Advanced” example. You mention it as a “very simple example”. There is a discrepancy here.

    Maybe what Cairngorm needs is better documentation? For instance, if what you say is the intent of Cairngorm, that it isn’t prescriptive of the view, this should be clearly documented, including why and what the implications of this is.

    In short, Cairngorm needs a “Best Practices and Implementation Idioms” document, at least. People looking into using Cairngorm is looking for architectural advice. They will grab the examples, and do what they “say”. After all, what else should they do?

    I have read the posts of Paul Williams, and I think they are great. Indeed I link to them under “Further Reading” above. Even though their intent was to show how to unittest the view, they can be used to solve this problem with Cairngorm too.

  3. Theo - June 10, 2008

    @Steven

    I second what Per says, the publicly available information about best practices in Cairngorm is really bad. When evaluating application frameworks for Flex there isn’t much else you can do than read the documentation and the example applications, and here Cairngorm fails miserably.

    - The documentation is more or less nonexistent, the cairngormdocs.org page (which one must assume is the closest thing to an official hub for Cairngorm information) lists your tutorial written for Flex 1.5 as the first and only tutorial. The rest is just API references, which is utterly unhelpful if you’re not already using the framework. The “community” is a mailing list where most of the messages seem to have the subject “Help me”, and scanning the headlines of the blog gives me the impression that most of the content there is for those who already use the framework.

    - Then there’s the example applications, and it’s good that we now know that they aren’t worth looking at if we want to know how to really understand Cairngorm. The problem is that there doesn’t seem to be any alternatives. What comes after “advanced” if “advanced” means “simple”?

    On these points PureMVC fares much better, and factoring in architecture too there should be no doubt that if the choice is between Cairngorm and PureMVC, PureMVC wins hands down tied behind its back and blindfolded. That being said, PureMVC has it’s fair share of problems.

  4. lauren - June 10, 2008

    I’ll agree with Theo about Cairngorm not following through with very good examples, although outside blogs have started sharing a lot of good info.
    We spent a few days building sample projects in both frameworks and trying to decide between Cairngorm and PureMVC.

    While PureMVC has a longer learning curve (took us approx an entire half day to work our way through an intermediate example), I feel it has a lot more to offer especially for those not used to using the MVC architecture.

    It seems a shame that most larger companies are going with Cairngorm by default since it has been endorsed by Adobe and not even considering alternatives like PureMVC.

  5. Almog Kurtser - June 13, 2008

    Hi,
    You’re absoultely right about how Cairngorm needs better documentation for best practices.
    At first, when I’ve started using Cairngorm, I follow simple examples.
    Most of them were far too simple, and as a result of their simplicity, they just didn’t demonstrate best practices for enterprise application.
    For example, the use of singleton mondel, can be misused as a single source for databinding, this can work just fine with very small app, but as the app needs to scale up, you’ll soon find all your views obscenely violent the Principle of Least Knowledge (LoD) by digging way too far into objects (_model.orders.lastorder.price…).
    Of course this can be avoided, if views inject the appropriate VO to their child.

    The one big problem I find with Cairngorm is its core singletons – i.e CairngormEventDispatcher and the evil evil real singleton -ServiceLocator.
    These can give you some really hard time building modular application.
    I found arc90 Modular kit, which solves some of this problems by using the CairngormEventDispatcher as Multiton.

    Also, I really recommend reading Jesse Warden 10 tips for using Cairngorm:
    http://jessewarden.com/2007/08/10-tips-for-working-with-cairngorm.html
    he’s got some very good points there.

  6. The Burgeoning Openly Owned Web » links for 2008-06-22 - June 22, 2008

    [...] Tech Per » Blog Archive » Patterns of GUI Architecture in Cairngorm and PureMVC If you really want the bloat and complexity these MVC frameworks are great… otherwise check out EasyMVC lightweight and no dependencies! (tags: flex puremvc cairngorm patterns actionscript) [...]

  7. PureMVC vs Cairngorm | Rich Internet Applications - June 23, 2008

    [...] just read this post about comparing Cairngorm and PureMVC frameworks ( from design GUI side). Author said: “So is [...]

  8. robin bakkerus - June 23, 2008

    Very interesting article.
    Could you also say something about ‘Mate’. Looks like a promising flex framework as well.

  9. polesen - June 23, 2008

    @robin: I have mate on my radar, but currently, I do not know enough about it, to express my feelings on it. Sorry!

  10. Alain - June 27, 2008

    We decided to chose PureMVC instead of Cairngorm mainly because of the notification system that really allows us to implement loosely-coupled MVC components.

    Furthermore, we wrote our own framework on top of PureMVC to allow more ‘graceful’ handling of notifications (instead of switch statements) and to provide other convenient features such as centralized configuration (based on conventions) in an mxml file, logging service, etc.

    The framework is not perfect and the learning curve is quite long for new developers but the result in terms of application design is well worth it, imho.

  11. polesen - June 27, 2008

    @Alain:

    Interesting. Are these extensions to puremvc something you have published (or are considering to publish) in some useable, possible open and free :-), form?

    If not anything else, then maybe just the ideas and examples, for others to follow or simply learn from?

  12. Alain - July 1, 2008

    Well, the customer for which I’m working owns the source code for the framework (team effort), so I can’t take the decision to release it on my own of course but they (IT architecture team) are open-minded guys and have already considered to release it as an open-source framework.

    The problem is that they must have agreement from the management knowing that corporate communication is rather controlled. :(

    Nevertheless, I can still push to see if it’s possible to release it under one form or another.
    In this case, I’ll let you know.

  13. More PureMVC Links « The Algorithmist - July 14, 2008

    [...] Discussion of Cairngorm and PureMVC as patterns of GUI architecture. [...]

  14. Generation 5 » The Role Of The Model in Silverlight, GWT and Javascript - July 18, 2008

    [...] in client-side RIA frameworks. There are only a few client-side frameworks today (for instance, Cairngorn and PureMVC) but I think we’ll see exciting developments in the next year: subscribe to the Gen5 RSS feed [...]

  15. andrew - July 30, 2008

    I recently went through the whole Cairngorm vs PureMVC framework selection process. Coming from the Java world, I am so tired of these framework battles (EJB3 vs Spring, Annotations vs XML, Glassfish vs Tomcat, blah blah!), and I was a little annoyed to be doing this AGAIN in flex. But I choose PureMVC. I had previous experience with this thing called Tango which had the universal Model Singleton pattern and it was a horrible mess. At a certain level of complexity, you have no idea who is updating what in the model, and the model is a mix of UI stuff, business objects, weird logic, and just gets nasty. It gets way out of control. The decoupling if the model from the view in PureMVC was one of the main reasons it won out. Also the docs were good, especially the best practices doc. In the end, I don’t want some crappy sample app, I want a deeper architectural understanding. It’s not perfect, but it is well thought out and the community is good and improving. If you ask a question on the forum there is a good chance Cliff, the creator of the framework will answer (as of now, July 08).

  16. Tech Per » Blog Archive » 4 Things To Hate About PureMVC - October 5, 2008

    [...] I have written about how puremvc takes a stand on patterns of gui architecture while Cairngorm does not. I have also proclaimed to colleagues, that I do not find puremvc [...]

  17. 比较PureMVC和Cairngorm的GUI架构 | Bonashen.com - January 12, 2009

    [...] Olesen在Tech Per上发了一篇博客文章,比较两个最流行的Flex框架,PureMVC [...]

  18. Zhidao - April 20, 2009

    @Alain:

    Quite interested on

    “Furthermore, we wrote our own framework on top of PureMVC to allow more ‘graceful’ handling of notifications (instead of switch statements) and to provide other convenient features such as centralized configuration (based on conventions) in an mxml file, logging service, etc.”

    I am facing same problem. And planning to use “naming convention” to load the processor which maybe controlled by IoC.

    Same question as
    ” polesen Says:

    @Alain:

    Interesting. Are these extensions to puremvc something you have published (or are considering to publish) in some useable, possible open and free :-), form?

    If not anything else, then maybe just the ideas and examples, for others to follow or simply learn from?

  19. andy.edmonds.be › links for 2008-06-22 - April 7, 2010

    [...] Tech Per » Blog Archive » Patterns of GUI Architecture in Cairngorm and PureMVC If you really want the bloat and complexity these MVC frameworks are great… otherwise check out EasyMVC lightweight and no dependencies! (tags: flex puremvc cairngorm patterns actionscript) [...]