Architectural Atrocities, part 9: Cairngorm’s Model Locator pattern

From time to time I re-read the introductory articles on Cairngorm just to remind me of why I don’t use it and never will. This installment of the Architectural Atrocities series is a critique of the Cairngorm framework, and the Model Locator pattern in particular.

The Cairngorm framework is hailed by many as the framework to learn if you are a Flex developer. It claims to teach good practice and promote reusability, low coupling and rapid development, just like every other framework ever conceived. How does it live up to this goal? Not very good in my opinion. I would argue the opposite: Cairngorm promotes bad solutions that lead to less reusability and tighter coupling, especially when it comes to how applications should bind to the model. There are however ways to alleviate the worst aspects of this, and at the end of this article I outline one way you can make your Cairngorm applications less tightly coupled to the model.

This was meant as a thorough critique of the whole Cairngorm framework from an architectural standpoint, but I have limited myself to the part centered around the Model Locator pattern. If you scroll down a bit you will understand why; there is so much to say just about that part of the framework, trying to cover it all in one article would be too much. I might return to the other aspects of Cairngorm in other articles.

Model Locator and global variables galore

Let’s start off with how the introductory articles describe the Model Locator pattern:

Watching developers fall repeatedly into these traps, the Adobe Consulting team conceived the Model Locator pattern as a best practice for Flex developers to adopt. The Model Locator pattern is unique because it is not a pattern we borrowed from the Core J2EE Pattern catalog. Instead, we created this pattern particularly for Flex application development. Our motivation was to have a single place where the application state is held in a Flex application and where view components are able to “locate” the client-side model that they wish to render. Our Model Locator pattern strategy encourages the use of data binding so that view components bind directly to the client-side state held in the single instance of the ModelLocator class. In this way, whenever the model is updated in ModelLocator, all view components binding to the model receive notifications (through the underlying data-binding mechanism) and update themselves to render the new model on the client.

From Adobe Developer Center: Developing Flex RIAs with Cairngorm Microarchitecture – Part 2: Keeping State on the Client.

Translation:

We though all the patterns in the J2EE catalog looked too complicated so we came up with this idea of using global variables instead, it’s much easier.

Jokes aside, the Cairngorm Model Locator is an anti-pattern: a commonly reinvented bad solution. Model Locator is global variables in disguise and does the opposite of what a design pattern should do. Instead of promoting code reuse, programming to interfaces and making the parts of an application less coupled in general, it ties everything tightly to a global variable — just count the design errors.

The problem with Cairngorm’s Model Locator is mostly in how it is explained, promoted and used. The idea of having one interface fronting your model isn’t bad as such, but doing it the way Cairngorm does it is. Cairngorm promotes the use of global variables and all the problems that brings, and it does so completely unnecessarily. You can easily architect your application in such a way that there is only one instance of the model front without relying on global variables as Cairngorm does (and I outline one way to do this below).

Even in the Cairngorm examples there seems to be some confusion as to what good the Model Locator pattern does. In the Cairngorm Store example application some components bind directly to the Model Locator instance but some don’t and instead get their data from their parent. I haven’t seen any rationalisation for this, so I’m going to propose one myself: binding to a global variable makes components less reusable. For some reason, in Cairngorm this wisdom applies only to some components and this makes me think that the designers of the framework (or at least the ones writing the example application) at least subconsciously have understood how bad global variables are.

There is a pattern to which components bind directly to the model and which don’t: Mostly it’s the scaffolding — the components that provide the crud to display other components — that binds directly, and leafs — the components that display data and don’t have any major subcomponents — that get their data from their parents.

The realisation that components get less reusable when they bind to a global variable is good, and you may argue that it doesn’t matter if the scaffolding is not reusable so it doesn’t matter if it binds directly to some global object. But there is more to this than being reusable, all the other bad things related to using global variables still apply: it’s harder to test, it’s harder to replace the model, it’s harder to replace the scaffolding, etc. By binding directly to a global variable you have locked your application into using one specific implementation as your model, and one mode of retrieval (the getInstance method). In Cairngorm you can’t change the implementation of the model without changing all you scaffolding views. Programming to concrete implementations, and modes of instantiation is the opposite of good object oriented design.

Monostate

You might have noticed that I don’t use the term “singleton” in the discussion above. The reason is that the Cairngorm Model Locator implementation as it’s described in the introductory articles isn’t an example of the Singleton pattern, but Monostate (newer versions of the framework does this a little different, but I’ll get to that). This is how it’s introduced in the articles:

Having all the attributes on the Model Locator pattern as static attributes ensures that the Model Locator pattern is a simple implementation of a singleton.

From Adobe Developer Center: Developing Flex RIAs with Cairngorm Microarchitecture – Part 2: Keeping State on the Client.

The Monostate (anti-)pattern can be described as a class that has only static members so that all instances of it share the same data. In most real-world examples of Monostate instances aren’t even created but the class itself is used as an instance. There are numerous examples in the Flash API:s, for example ExternalInterface and Mouse, but most were thankfully cleaned out in the transition to ActionScript 3.

In an all-static class (such as the one in Model Locator) is nothing but a namespace (i.e. package in ActionScript). It serves only the purpose of bundling together a number of variables and functions. This is indeed an anti-pattern and a regression to procedural programming.

However, I should say that it seems like the recommendations have changed since the introductory article was written. In the latest version of the Cairngorm Store example the model locator is a proper singleton and has no static members except for some constants. This is just a change in implementation — the model is still used as a global variable.

Marker interface madness

Besides promoting anti-patterns, the Cairngorm designers don’t seem to understand the basics of interfaces. In the framework there is one called ModelLocator which, according to the documentation, Model Locator implementations should implement.

The interface doesn’t declare any properties or methods, it is an empty, so-called marker interface. Marker interfaces are generally used to show that some objects have capabilities or properties beyond what is possible to describe in code, usually metadata of some sort. Using a marker interface is almost always a sign that the language used lacks other mechanisms for declaring metadata forcing the programmer has to resort to a hack to do it.

While there is no excuse to use marker interfaces in Flex 3, the current version of Cairngorm targets Flex 2, which didn’t really support persistent metadata, so the designers of Cairngorm could be forgiven for resorting to this hack. They could be forgiven if there was actually any point in the interface to start with.

The framework never uses the interface nor does the example application (besides having it’s Model Locator implementation implement the interface, obviously). So what then could it be good for? Let’s analyse the situation: there is an interface that Model Locator implementations should implement but the interface doesn’t require anything of the implementing class and neither the framework nor applications built on the framework enforce its usage nor use it in any other way. Moreover, the interface is supposed to be implemented by all-static classes, essentially glorified namespaces. Given these facts, what reason could there ever be for having the interface? I can se none. In fact, all I can see are clueless designers trying to check off patterns in the J2EE catalog.

As I mentioned above, some of the details of the Model Locator pattern has changed in the later versions of Cairngorm. Perhaps this madness has been purged you think? No, in fact it has gotten even weirder. Instead of the interface ModelLocator there is now two interfaces: ModelLocator and IModelLocator, the former extending the latter (the latter former remaining for backwards compatibility, I assume).

Guess what? None of them are actually used in the framework nor in the example application. Now there are two nonsensical and unnecessary interfaces.

Documentation

As I mentioned I’ve read the introductory articles a few times, and in all earnestness wanted to learn the framework. I’ve looked through all the resources I’ve come over, the example applications, other developer’s blogs and even browsed the framework code.

The introductory articles are old, they were written for Cairngorm .99 (the current version is 2.1) but they are still the most recent beginners guide that can be found through the Adobe Labs page on Cairngorm and the cairngormdocs.org page. There have been significant changes in the framework between .99 and the current version, at least enough to warrant a rewrite, or at least a new beginners guide.

Apparently the Cairngorm community thinks that examples are better than explanations. From the cairngormdocs.org page you can download three example applications, one beginner, one intermediate and one advanced. I’ve downloaded all three and all came completely without any explanation, it was all just code. Code is all very good if you know how things work, and if it’s documented in a friendly way.

The code in the beginner example was documented by the department for the blindingly obvious:

/**
 * The constructor, taking a ContactVO
 */
public function AddContactEvent( contactVO : ContactVO ) 

And the intermediate wasn’t much better:

// was the Alert event an OK
if ( cEvent.detail == Alert.OK ) {

To be fair, the intermediate example did contain more helpful comments too, but not enough to make it usable. The advanced example, the Cairngorm Store which I’ve talked about above had some documentation of the business logic, but that was more or less it.

If you read Jeff Houser’s Learning Cairngorm series it’s almost laughable how hard it seems to be to get started.

But I hear you protest, “there is lots of documentation! there is extensive API documentation!”. Well, if you’ve read this blog for a while you should know what I think about API documentation.

What’s in a name?

I’m all for using British English, but when it comes to programming I think that there is only one way to keep everyone sane: use American spelling always. If that, for some reason (I can’t think of any) isn’t possible the next-best thing to do is to be consistent. The designers of Cairngorm don’t seem to care. There are examples of both British spelling as in initialiseCommands (FrontController) and American spelling as in initialized (ViewHelper). This is just sloppy.

And while I’m on the subject of naming, what about the name “model locator”? Using “locator” in a class or interface name implies that objects of that type are used to locate models, perhaps because it implements the Service Locator pattern. In Cairngorm a “model locator” is the model. (The other “locators” in the framework, ServiceLocator and ViewLocator, are actually locators in the Service Locator pattern sense. Did I mention that good and consistent naming is a virtue in framework design?)

I also have a pet peeve: interface names prefixed with “I”. I’ve written about this before so I won’t go in to the details. It suffices to say that if you prefix your interfaces with “I” you don’t know how to use them properly. As we’ve seen above, the Cairngorm designers have some problems with their understanding of interfaces, so this shouldn’t come as a surprise.

The upside

Because I haven’t looked into the details of the other parts of Cairngorm besides Model Locator I’m not prepared to write off the framework completely just yet. However, Model Locator is such a mess of anti-patterns and bad practice that as it is I wouldn’t touch Cairngorm unless forced under pain of death or given substantial amounts of cash in advance.

Having said that you might be surprised that there are a few simple things that can be done to alleviate the worst aspects of Model Locator.

How to de-uglify your Cairngorm views

This code is in every single scaffolding component in the Cairngorm Store example:

[Bindable]
public var model : ShopModelLocator =
    ShopModelLocator.getInstance();

just a few simple commands can replace that with this:

[Bindable]
public var model : ShopModelLocator;

…and suddenly you have a component that instead of binding directly to a global variable declares a dependency: a ShopModelLocator. The component is no longer responsible for retrieving it itself, instead that responsibility is passed on to other components that want to use this component.

You might think I haven’t done anything here, all that’s changed is where the singleton is retrieved. That is true, but there is so much more to this. In my version there is nothing that says that ShopModelLocator has to be a singleton. As long as ShopModelLocator doesn’t change it’s public interface it can be completely rewritten, without this component ever having to worry about it. Ideally, ShopModelLocator should be an interface (and be called something less confusing), that way there is no limit to how much the actual implementation could change. There could be one implementation used for testing, one used in development and one used in production. You could have one implementation per back-end, or you could completely rewrite the model and have a bridge between the new version and old to avoid having to rewrite old components. The beauty of it is that it wouldn’t matter to the component. Using the Model Locator of Cairngorm the best you can get is hiding something ugly behind the singleton, but you can’t have different versions for testing and production without replacing the source code of the Model Locator instance.

Dependency injection

What I describe above is called Dependency Injection and it more or less the the opposite of Cairngorm’s Model Locator: instead of components going out to find the data they need themselves, it is injected into them by the parent. This means that you get components that know nothing about when or where they are used, they know just enough to do what they are supposed to, almost the definition of reusable code.

It’s ironic that just before introducing the Model Locator pattern the author of the introductory articles on Cairngorm dismisses dependency injection:

Additional strategies include passing data up and down through MXML component instantiations. Consider the following graphical representation of MXML components, where data is in a leaf node of the tree and is required in another developer’s leaf node. The only solution is to find a common branching point for both leaf nodes and then, from that branching point, pass the data down through the component chain with component instantiations, as follows:
<myView:MyComponent data="{this.data}" />
Once again, this is a strategy that is incredibly brittle to changes in the implementation of the view. It leads to regular errors because it incorrectly passes data down the chain somewhere. Debugging these errors is a laborious job of tracing the component paths to confirm that data has been correctly passed between components. It’s a frustrating task.

From Adobe Developer Center: Developing Flex RIAs with Cairngorm Microarchitecture – Part 2: Keeping State on the Client

This is utterly false and uninformed. Especially since the author then goes on to propose global variables as a better solution.

What I think the author refers to is the fact that the data property that many Flex components have is untyped, so if you pass all data in that property you will not get any errors if you pass an object of the wrong type, instead you get seemingly unrelated error much further down the line. This is true, but using the data property as a method to populate components is pretty stupid, it works fine for item renderers but should be avoided in all other situations (data is enforced by the mx.core.IDataRenderer interface and its raison d’être is to make all view classes in Flex work as item renderers).

Components should declare their dependencies using properties with specific types (e.g. products of type Array or maxItems of type int). If the component then changes you will get compile-time errors telling you that the properties you are setting don’t exist or have the wrong type, or you get runtime errors when setting the properties telling you that that there was a type error. If the calling code is in ActionScript you will get most type errors at compile time, but with MXML that is not always the case.

Getting compile-time errors because your views have changed isn’t an example of a brittle architecture, quite the contrary.

Conclusion

My critique was written based on the information available from Adobe Labs page on Cairngorm and the cairngormdocs.org page, the introductory articles, the example applications and the source code of the framework itself. There may be resources I have not found, but if that’s the case it’s just another bullet under the header “Documentation” above. If it can’t be found by beginners then what good is it?

What I’ve seen does not impress me, and I find it surprising that Cairngorm has such a large following. It’s troubling to see global variables and other anti-patterns promoted as best practice by people who seem to be central in the Flex community.

I think that there already is quite a lot of criticism of the framework in the Flex community, and I think that the guys behind asserttrue.com really did a good job in their overview of Flex frameworks. Although not critical Jeff Houser has written about the problems of singletons in Cairngorm and Niel Webb explains the same problem and proposes a solution as well.

I expect to get some hate in the comments from you Cairngorm fanboys, I don’t mind, but please be civil.

56 Responses to “Architectural Atrocities, part 9: Cairngorm’s Model Locator pattern”

  1. David Spurr Says:

    Really well-reasoned set of arguments there, I did look at Caringorm once I got used to the Flex framework itself but I found it (or at least the way the examples recommended using it) to tended towards being more tightly coupled to your code than I want from a framework. I ended up going the pureMVC route and believe I made the right choice.

  2. Bjorn Schultheiss Says:

    Yo Theo,

    I agree. The ModelLocator is useless.

    Another problem is that it relies on databinding and as a result the data that is showed on your views can be stale..

    For example if your using a viewstack, databinding will only update the view that currently visible. Data Binding will not update the invisible views, and when they are switched to visible they have the possibility of showing stale data, since data is also stored locally on each of the Flex components. (eg. colloection property in ListBase)

    So then you have to monitor two models. The data on your modelLocator and the data stored in your view components.

    This gets nasty to debug (and test).

    Theoretically I like the idea of a single access point to your Model.. But using ModelLocator doesn’t mean you only have a single copy of that data as I illustrated previously…

  3. Joe Rinehart Says:

    clap clap clap clap

    Very nicely written. The first large-scale application I wrote in Flex was based in Cairngorm, using many of the anti-patterns you’ve discussed here. As it grew, it became this glop of global variables and procedural scripts (sorry, Commands…).

    I’ve come a bit more to grips with CG recently, as it’s a de facto requirement in many of the Flex shops I’ve worked with. The solution I’ve found is to simply use “less” Cairngorm, primarily using it to manage server-round trip sequences. Less and less frequently do my commands update anything in the model locator – more and more frequently, they update an instance of something passed along as part of their related Event.

    Anyhow, glad to see I’m not the only person who feels that working with CG feels like a big step back.

  4. Marcel Panse Says:

    Man, couldn’t agree with you more ;-)

    grtz marcel

  5. Anonymous Coward Says:

    Nice job Theo!

    You should know that you haven’t even scratched the surface here.

    Every facet of UI development that requires any amount of intellectual rigor is instantly resolved in Cairngorm by going global and restating your intent in a multitude of files.

    Just remember that context dependence isn’t a problem when you don’t write unit tests, don’t support modules and your application footprint is so large that you’d never load one into another – essentially when you enforce the fact that the running, production application is the only context you will ever support.

    In the time that I’ve been working with the Flex framework, I’ve come to understand that the crux of Flex development is simply component development. And that is hard because the framework itself makes many of the same assumptions as Cairngorm about globals, duplication and context – they’re just ever-so-slightly more hidden.

    To be fair, I have to constantly remind myself that many people are able to create some really great applications with both Flex and Cairngorm, and they’re able to do this in a relatively small amount of time. Even though I may strongly disagree with just about every tradeoff made, these technologies irrefutably contribute to real business value.

  6. Matt Przybylski Says:

    I’ve griped MANY times about Cairngorm and why it is used, although my reasons are a bit different than yours. Yours are based on the improper use of design patterns within Cairngorm whereas mine are that using CG is just overkill on a lot of projects. What I can do in CG in 5 steps I can normally do regularly in one. I understand that it is a standard in some places but come on, is it really necessary to use it on relatively simple projects? Man, CG is annoying. /rant

  7. zwetan Says:

    nice article even if I find you’re maybe too harsh on some points.

    Before commenting further I must say I tend to avoid using frameworks, I’m more into writing directly the code that is needed and then if that make sens yeah use some pattern or maybe an architecture as MVC afterwards, but not tying me up right from the start into any architecture.

    So, about the monostate, sorry I don’t agree “In an all-static class (such as the one in Model Locator) is nothing but a namespace (i.e. package in ActionScript). It serves only the purpose of bundling together a number of variables and functions. This is indeed an anti-pattern and a regression to procedural programming.”

    this is not an anti-pattern per se, this can be usefull, ok maybe not in the logic of an MVC, but even though don’t trash that pattern altogether it got some uses, like a single access point for a configuration.

    I find myself in a lot of cases using the monostate, and god forbid if I shock anyone, I use it to save configuration states, even if everyone tell you that the logic of a monostate is to not preserve state, sorry it can and it’s easy, readeable and well named.

    About interfaces prefixed by “I”, I understand your point, especially if you are in a double dispatch situation you don’t even want people to view that it is an interface you want them to see it as a type, but still using “I” for interfaces as a naming convention is not that bad, well at least it does not bother me that much and I use it too but consciously.

    If I consider an interface as a “template” I will prefixe it “I”, if I consider an interface to be a type then no “I” prefix.

    As a final point I would like to say that Flex and AS3 programming are still new and we have much more to explore, I don’t believe that MVC is the end-all-be-all of architecture, we can use dynamic programming, prototype, code behind (mxml->as3, or as3->mxml), etc.

    but still criticism is good, it makes things evolve and make people think :).

  8. jimmy fung Says:

    Hey dude, Your architectural-atrocities posts are excellent. Interesting and thought provoking. Thanks.

  9. Theo Says:

    I was expecting hate, but I’ve never gotten this much praise before. Thanks a lot, it’s inspiring. Perhaps I should be even harsher next time =)

  10. Robin Hilliard Says:

    >I expect to get some hate in the comments from you Cairngorm fanboys, I don’t mind, but please be civil.

    You wont get any from me, although I must say your post tends towards the highly vitriolic in many places.

    I agree that people don’t always use the ModelLocator as intended, I made the point about the danger of global variables on cairngorm-devl just last week:

    http://tech.groups.yahoo.com/group/cairngorm-devel/message/209

    >so I’m going to propose one myself: binding to a global variable makes components less reusable.

    How? You write a model per application. In your application code you write . X still has no dependency on the Model, the dependency is on the type of data, which is probably a VO and as such no problem.

    >There is a pattern to which components bind directly to the model and which don’t: Mostly it’s the scaffolding — the components that provide the crud to display other components — that binds directly, and leafs — the components that display data and don’t have any major subcomponents — that get their data from their parents.

    >it’s harder to replace the model

    The former is there for the latter reason, no? Reference the model in one place and pass bits of it out through the composite view as required.

    > There are numerous examples in the Flash API:s, for example ExternalInterface and Mouse, but most were thankfully cleaned out in the transition to ActionScript 3.

    Don’t forget Math. So you’d rather you had to create instances of all these core services e.g. var x = new Math().sin(y) instead of var x = Math.sin(y)? Do you really mean that? No one seemed to pick this up in the comments, assuming they actually understood what Monostate meant.

    The reason it changed to singleton is that AS3 doesn’t support binding to static variables, so we need an instance – easy.

    > so-called marker interface.

    Hah! I raise you a so-called “package” and two so-called “methods”. It sounds more sinister that way, but really are marker interfaces that uncommon? They’ve been around for at least 7 or so years and used in more than one OO language. I think they’re a great way to communicate intent to other developers.

    > Given these facts, what reason could there ever be for having the interface?

    Communicating intent to other developers. The compiler isn’t the only one reading your code.

    > there is now two interfaces: ModelLocator and IModelLocator, the former extending the latter (the latter remaining for backwards compatibility, I assume).

    No the former is for backward compatibility. The just renamed the interfaces to follow conventions in other languages.

    > I’m all for using British English, but when it comes to programming I think that there is only one way to keep everyone sane: use American spelling always.

    I would say something about this but I promised to be polite.

    > I also have a pet peeve: interface names prefixed with “I”. I’ve written about this before so I won’t go in to the details. It suffices to say that if you prefix your interfaces with “I” you don’t know how to use them properly.

    Oh dear, better let the developers of the Java and Windows APIs know about that one – thank god you’ve written about it.

    > Because I haven’t looked into the details of the other parts of Cairngorm besides Model Locator I’m not prepared to write off the framework completely just yet.

    I have to say I spent a few minutes searching for my jaw under my desk when I read that one. You’re writing a critique of a framework you haven’t actually finished reading the source code of? I suppose it wouldn’t be too much to ask you to dash off an application or two in it before you decided to write your article?

    BTW I’ve decided that PureMVC is garbage – I haven’t looked at their site, the code, spoken to the authors, read a presentation on it or anything like that, I just think the name is… funny. There should be a whole series of blog articles in that one.

    > …and suddenly you have a component that instead of binding directly to a global variable declares a dependency: a ShopModelLocator.

    Erm – both examples have a dependency on the ShopModelLocator class – isn’t that what matters?

    > In my version there is nothing that says that ShopModelLocator has to be a singleton.

    And in Cairngorm there’s nothing to say that a ModelLocator has to be a singleton. In fact I architected a production Flex 1.5 application with over 2,100 classes in the client where most of our models were instance based, not singletons (this was because we had an MDI interface – see http://www.rocketboots.com.au/blog/index.cfm?mode=entry&entry=9B81372E-E081-51EF-A7BA448EA83C96A6)

    Cairngorm is pretty unprescriptive about how you do things.

    > What I describe above is called Dependency Injection and it more or less the the opposite of Cairngorm’s Model Locator: instead of components going out to find the data they need themselves, it is injected into them by the parent.

    This is exactly what you were upset about at the top of your article when you talked about “leaf” components – the parent view injects the dependency into the child view. Yes it is a good thing, and yes it is used all the time to bind views in Cairngorm applications.

    > I think that the guys behind asserttrue.com really did a good job in their overview of Flex frameworks.

    See my comments towards the bottom of this thread on the framework shootout presentation:

    http://groups.google.com/group/flashaussie/browse_thread/thread/9c0b90e83c03435b/e8fb6a6481536f4b?lnk=gst&q=robin#e8fb6a6481536f4b

    > For example if your using a viewstack, databinding will only update the view that currently visible.

    Bjorn you know better than that (:| – that’s due to the creation policy of the view stack and nothing to do with Cairngorm.

    > Less and less frequently do my commands update anything in the model locator – more and more frequently, they update an instance of something passed along as part of their related Event.

    Joe, more than half the Cairngorm apps I’ve written (in Flex and Flash) would pass references to elements of the model up in the event – it’s perfectly ok to do this, in fact we had to do it when we had instance based models.

    > Anyhow, glad to see I’m not the only person who feels that working with CG feels like a big step back.

    From what? Joe I’m sort of disappointed that as a popular framework author yourself (and author of another Flex framework) you are making such broad brush negative statements. How do you feel when you read comments like this about Model-Glue? What would you say to those people?

    > but still criticism is good, it makes things evolve and make people think :).

    I would add to that, “if it’s INFORMED critisism”. Seriously I really (and I mean really) don’t understand why you’re commenting on a framework you haven’t even finished looking at, and why Bjorn, Joe, Marcel and coward seem to falling over themselves to pat you on the back for doing so.

    Thanks, Robin

    PS: So, lets see how civil we can keep this then :-). I will make time to answer real questions about the framework or how it’s used in practice (because it’s important to me to get good information about Flex architecture practices out in the community), but I don’t have time for flames.

  11. Theo Says:

    This is in reply to Robin Hilliard.

    First of all, my apologies for your messages being marked as spam, I can only blame Akismet. I’ve changed the time on your comment so that it would appear after one of mine (which I posted before I found yours), it wouldn’t make much sense otherwise. I hope you don’t mind.

    Re: One model per application and models are not replaceable

    This is another problem with Cairngorm it encouranges you to write bad non-reusable models. You are encouraged to mix the business logic part of the model with application state. Perhaps I should have made this clear in the article: I really think you shouldn’t have application state (e.g. which view should be visible) mixed with model data (e.g. this is a list of products or this is the currently logged in user). The way it’s described in the Cairngorm articles and examples the model is tightly coupled to the view, and the view is tightly coupled to the model, of course you can only have one model per application in that scenario!

    You can write one model and then several applications on top of it if you keep it model-data-only and don’t mix in application specifics. One example (from an application I’m currenty working on) is of you want to extract a part of the application and also use it independenty. In my case it’s a preview which can be used inside the application or standalone, but it still uses the same model. The model doesn’t contain anything that is application specific, it is only a representation of the data and actions available in the system. The stand alone preview doesn’t use the whole domain of the model, but it can still use it because the model is completely agnostic to what is using it. At any later date I could extract another part of the application to be used standalone, without chaning the model.

    This is the point of MVC, to keep the model, the view and the controllers separate. Cairngorm “best practice” doesn’t do that.

    Re: Math as monostate

    Math isn’t a Monostate, but it’s an all-static class. The reason why it’s not a Monostate is that it keeps no state at all, instead it’s a pure namespace. I don’t like it and I think it should have been replaced with a package containing public functions (like the functions in the flash.utils package, describeType for example). The reason it is not is that it specified by the ECMAScript standard (that doesn’t make it good, though, just understandable).

    One could argue that ExternalInterface isn’t a Monostate for the same reason, but I think that it actually keeps some state, at least it fronts some kind of state (for example which callbacks are registered).

    Re: Marker interfaces

    Marker interfaces are not unusual in languages that lack metadata, but in all examples I’ve come across the interfaces have actually been used somehow, objects tested if they implement it and things like that. In Cairngorm IModelLocator just is, it’s not used. Nothing would change if you didn’t implement it. If you can remove something without changing the system, that something is very likely unnecessary.

    This is an imagined conversation between a Cairngorm guru and his (somewhat rebellious) disciple:

    • Oh, and your model should implement this interface.
    • Why?
    • Oh, no reason, I just want you to be aware that your model is a model.
    • Hmm, I was already aware of that thankyouverymuch, after all it’s called M O D E L.

    If you want to make other developers aware that your model is a model, call something ending in “Model”, if you need it marked so that it can be handled differently by the framework, use metadata or if that is not possible, indeed use marker interfaces. Just don’t use marker interfaces to communicate intent, that just means your namning isn’t good enough.

    I challenge you to give me an example where marker interfaces could not be replaced by metadata or better naming.

    Re: “both examples have a dependency on the ShopModelLocator”

    Yes, both examples have a dependency on a ShopModelLocator, but the difference is that my version declares it as a dependency to be filled by someone else, the Cairngorm version doesn’t and instead retrieves it itself. The Cairngorm version has coupled itself to a concrete implementation, my version has just a dependency to an interface. I should add that the actual implementation of ShopModelLocator doesn’t have to be the same in the two versions, perhaps the example would have been more clear if I also renamed the type in my example. What I’m getting at is that if you use an abstract type and dependency injection you can reuse, if you use a concrete type and global variables you can’t.

    Re: there’s nothing to say that a ModelLocator has to be a singleton … Cairngorm is pretty unprescriptive about how you do things.

    The Model Locator pattern, which is the topic here, is pretty explicit on this point. I’m sure you can program with Cairngorm without following all it’s advice, and that is in fact exactly what I’m proposing. I even suggest a way to work with Cairngorm without resoring to the Model Locator pattern as you saw. I would suggest not using Cairngorm at all, but if you do, there are things you can do to fix the worst problems. Good for you that you don’t use global variables in your project.

    Re: Dependency injection already in Cairngorm

    I don’t mention DI by name when I talked about the inconsistencies in how the Cairngorm articles work with the model, but it’s true that the leafs are injected with their dependencies (but calling this DI would mean that every time you set a property it would be DI). This is good, but my point there was that somehow the designers of Cairngorm seemed only subconsciously aware of that being a good thing, because they don’t apply it on a larger scale, instead resorting to global variables in the scaffolding.

    Re: …would add to that, “if it’s INFORMED critisism”

    Where by “informed” you mean “agreeing with your opinion”, or what? Do you seriously think that I would, or even could write all that without having looked through the thing? If you do, I don’t think you understand the word “details”.

    It is true that my criticism is from an outside view because I don’t use the framework, and from the information available about it wouldn’t consider to use it either. The article explains my reasons, but it goes only as far as the Model Locator pattern. When I have the time and if I feel the urge, I will go in to the details of other aspects of the framework. That doesn’t mean I haven’t looked at the other aspects, just that I haven’t gone into the details, and that I haven’t compiled my thought on them yet.

    It’s obvious that you don’t agree with my criticism but a few actual Cairngorm developers do seem to, as you have seen. I even had a Cairngorm user proof read the article just to see that I didn’t miss that things have changed since the documentation and examples were written. Just because you don’t agree doesn’t mean that other Cairngorm users can’t, at least consider the possibility that they actually agree and not only want to praise me (why that would be more important to them than protecting the honour of Cairngorm escapes me).

  12. Robin Hilliard Says:

    > This is another problem with Cairngorm it encouranges you to write bad non-reusable models.

    I don’t think non-reusable models are much of a loss – even in complex apps they are usually a class with a short list of 3 to 10 value object properties and a few boiler-plate lines of singleton machinery. The value object classes themselves remain reusable.

    > You can write one model and then several applications on top of it if you keep it model-data-only and don’t mix in application specifics. One example (from an application I’m currenty working on) is of you want to extract a part of the application and also use it independenty.

    You can (and we do) break up your model into multiple classes along reuse lines if you think there’s an opportunity for reuse.

    > You are encouraged to mix the business logic part of the model with application state. Perhaps I should have made this clear in the article: I really think you shouldn’t have application state (e.g. which view should be visible) mixed with model data (e.g. this is a list of products or this is the currently logged in user).

    If the logged in user affects the state of the view, then it definitely should be a part of the model. The trick is to keep it all use-case level concepts and not view dependant. A model variable called showLeftTreeControl is a definite no-no. A variable called processState changing from AUTHENTICATE_USER to SELECT_PRODUCTS is fine (using the language of the original use case). We often have variables in the model bound to currentState. If you follow this approach the model can work with many views and is not tightly coupled to the view at all.

    > This is the point of MVC, to keep the model, the view and the controllers separate.

    Separate yes. With no dependencies between each other – impossible! see my presentation:

    http://onair.adobe.com/blogs/videos/2007/05/01/webdu-easy-as-mvc-architecture-and-frameworks-for-non-believers-robin-hilliard/

    Or slides of same:

    http://www.rocketboots.com.au/blog/index.cfm?mode=entry&entry=9AB6D9E6-E081-51EF-A7F1BD621B85AAE3

    But perhaps you will find that making the above distinction about naming and thinking about model variables resolves your issue. It’s subtle but I’ve learned that paying attention to the original intent of these patterns almost always turns out to be a wise move in retrospect.

    Regarding Monostate – well since it’s no longer used in Cairngorm we may as well drop it, we can agree to disagree about its exact level of evilitude.

    > I challenge you to give me an example where marker interfaces could not be replaced by metadata or better naming.

    1. Where your framework users couldn’t be bothered or might forget to change flex.config to make the metadata available at runtime, causing your framework’s model recognition mechanism to fail silently.

    2. Where you didn’t want to rely on describeType(), E4X and a regular expression to recognise that a class was a model because its name ended in -Model, and instead use the convenient instanceof operator.

    > Yes, both examples have a dependency on a ShopModelLocator, but the difference is that my version declares it as a dependency to be filled by someone else, the Cairngorm version doesn’t and instead retrieves it itself.

    Note that this is code in the sample application, not the framework itself.

    At some points, the view has to get a reference to the model. At those points it calls Model.getInstance(). The way this is usually used is:

    1. At the top level of composite views, where parts of the model are then passed out to child components by DI.
    2. When the data is very specific to a particular part of the view (e.g. a code table to populate a list of combobox options) and passing a reference to the code table model all the way down to the combobox would have been a pain in the neck. BTW this would often be a separate model class, so that we could move the code table model around with the UI containing the combobox.

    > I should add that the actual implementation of ShopModelLocator doesn’t have to be the same in the two versions, perhaps the example would have been more clear if I also renamed the type in my example.

    Ah well, that was sort of the crux of the matter so yes, the example would have been infinitely clearer. I’m all for avoiding concrete classes (ask anyone who saw my presentation on cfinterface at cfcamp – soon to be online) and that concrete class dependency is one of my least favourite things about singletons. But since in my book there is a very strong dependency on the model from the view anyway, it isn’t really something I worry about in the context of views locating models.

    > I’m sure you can program with Cairngorm without following all it’s advice, and that is in fact exactly what I’m proposing.

    And that’s what we’ve been doing for a long time, in Flex and Flash, but it doesn’t break the framework – you just use the bits you need. The framework itself is very un-prescriptive, perhaps the sample apps and docs are less so.

    > somehow the designers of Cairngorm seemed only subconsciously aware of that being a good thing, because they don’t apply it on a larger scale, instead resorting to global variables in the scaffolding.

    It’s a matter of practicalities. Cairngorm came out of several years of commercial Flash/J2EE development experience at iteration::two. Sometimes you need to get to your model quickly, from anywhere in the code. Having some global variables for access helped them, so they included that in the framework that they shared with the community. It wasn’t all an academic exercise in OO beauty, it was what worked, and kept their business growing.

    If I’m a Cairngorm fanboy, it’s because I have a lot of respect for people who shared a real, commercially tested framework with the community (they also shared ASUnit, BTW) and which I have to a large extend built my business around over the last four years. With the exception perhaps of Joe Berkowitz’s stuff (good presso at MAX 2006) it seems that the other Flex framework’s chief claim to fame is that they’re not Cairngorm, and when I dig I find they’re either the same, or that they claim they fix a problem which Cairngorm doesn’t actually have, are overly prescriptive or even worse that they introduce unnecessary dependencies in a way that misses the point of the MVC pattern.

    > Do you seriously think that I would, or even could write all that without having looked through the thing?

    And I quote:

    > Because I haven’t looked into the details of the other parts of Cairngorm besides Model Locator I’m not prepared to write off the framework completely just yet.

    The article was a lot broader in scope than just the model locator pattern. It’s really a tiny framework, as you said yourself ModelLocator is simply a marker interface. The entire framework without comments is probably less than 4 pages of code. I don’t understand why you would be in such a rush to write an article like this without looking at the other 3.9 pages. If I was being cynical I might think you were trying to stretch out the atrocities series a bit more – but of course I’m never cynical :-).

    > It’s obvious that you don’t agree with my criticism but a few actual Cairngorm developers do seem to, as you have seen.

    I’m on record saying that I’d rather people understood the MVC pattern and didn’t use Cairngorm than the other way around. Going through the actual declared Cairngorm developers:

    • Bjorn is a friend who came to one of our MVC seminars – he’s contacted me off-line about his issues, on the face of it they don’t seem to be fundamental problems with the framework.

    • Joe could have been helped by some of my comments here and in other threads and presentations I’ve referenced. Not all information out there on Cairngorm is helpful. I have been wanting to write a Cairngorm training course for some time now – people who’ve attended Flex courses I’ve instructed know that I have a fair bit of extra info about Cairngorm that I squeeze into the ends of the lunch breaks. As I said before, you have to stick to the intent of the pattern to make Cairngorm or any other MVC framework work for you.

    • Not sure if “coward” actually uses Cairngorm.

    • Matt, I’ve used Cairngorm on a Flash image viewer and it really helped. My lower bound for using Cairngorm is, well, low. Once you have the boiler-plate stuff set up it’s very quick to develop.

    • Zwetan doesn’t use frameworks.

    Ok, have to get to work.

    Thanks, Robin

  13. Jim Robson Says:

    I agree that the ModelLocator is one of the weak points of Cairngorm when compared, for example, with PureMVC – though my reasons are not exactly the same as yours:

    http://www.robsondesign.com/blog/index.php/2008/04/10/puremvc-vs-cairngorm/

    I also agree that the documentation for Cairngorm is very poor. The people who created the framework have not maintained up-to-date explanations or tutorials. The people who have put forth a valiant effort to make Cairngorm scrutable to beginners (e.g. the cairngormdocs.org folks) are volunteers who are just doing their best to help the community.

    Further, I am no fan of “marker” interfaces. They seem unnecessary almost to the point of being silly. Nor do I think the name “ModelLocator” is worth defending.

    However, I do think that some of your specific criticisms come from a lack of understanding of Cairngorm. This is not entirely your fault, considering the state of the documentation.

    In particular, the fact that you think of the ModelLocator as nothing but storage space for globals seems likely to be a result of the fact that you’ve read some antiquated (and highly simplified) articles and looked at a few sample applications. In general, sample applications are (necessarily) small and simple, and so it’s not surprising that the Cairngorm samples don’t fully represent how Cairngorm is used when building complex, real-world applications. The suggestions you make under “How to de-uglify your Cairngorm views,” for example, are not new ideas to anyone who’s developed a Cairngorm app of any size.

    It might be good, too, to give some serious consideration to this point made by Anonymous Coward: “Even though I may strongly disagree with just about every tradeoff made, these technologies irrefutably contribute to real business value.” There is something to be said for a system that works.

    As an aside, I don’t see the point in quibbling about naming conventions. Adobe has chosen to start the names of interfaces with an “I” so the Cairngorm developers decided to follow that convention. It’s a useful naming convention in that it makes it easy to distinguish the interfaces from the other classes. Doesn’t really seem worthy of argument one way or the other.

    But I will go along with your idea that everyone should standardize on American spelling! :-)

  14. Theo Says:

    Jim, and Zwetan:

    On the “I” issue, I really think this one goes deeper than just preference. My argument is that if you prefix your interfaces you set interface types apart, and it seems to me that the intent of setting them apart is because you view them as lesser types. What you end up with is an environment where class types are “normal” and interface types are special (as in “strange”).

    If anything it should be the other way around, prefix your class types to set those apart. Actually I don’t really think so, but if you think about it for a second, wouldn’t it change the way you write your code? If it would, then why do you think that interfaces should be prefixed?

    Why do you feel the need to set interface types apart? If it is to let the users of the API know that some types can’t be instantiated? Is it to show that some types are more abstract than others?

    I know it’s a widely used convention, but I question it nonetheless because I have still to hear a good reason for it other than “it’s convention”.

  15. Theo Says:

    Robin:

    Your two examples of when you think that marker interfaces could not be replaced can both be summed up by “because of laziness”, that is, in both cases you could use metadata (and it would be more appropriate) but you didn’t because you thought that it was too hard or you didn’t trust your users to be meticulous enough.

    I can agree that metadata is less common than interfaces so beginners might miss that point, but really, if you don’t trust your users to add metadata, how could you trust them to implement an interface? Besides, in Flex 3 as long as your framework was compiled to use a metadata tag all projects linking to it’s SWC will automatically keep that tag, so adding a metadata tag would be exactly the same as implementing an interface in terms of the work your users will have to do.

    The challenge still stands.

    Apart from that I think that you and I are mostly in agreement about what’s bad with Cairngorm. The difference is that you work with the framework and want to see a discussion about how it can be tweaked to serve your purposes and work around the bad stuff. I see it from the outside as something to potentially use, something to put under scrutiny and see if it’s worth the effort. From what I have seen it’s not, but I’m sure that if Cairngorm was a given, that I had to work with it whether or not I wanted to, I could find things to like. However, having the luxury to choose, I will not bother with Cairngorm because from what I can tell from the information available it’s not worth the effort.

    Because you have worked with the framework you have a different view of what Cairngorm is than my external picture, so of course you don’t agree with my view. I’m not criticising your use of Cairngorm, but the use of Cairngorm as it is explained, promoted and exemplified in the available documentation and example applications.

    I’m happy that you can use Cairngorm in a way that avioids many of the problems, but that doesn’t excuse the bad practice promoted by the documentation and examples.

  16. Theo Says:

    For the benefit of Robin I thought I should add clarification of the sentence that seems to be a red sheet for him:

    “Because I haven’t looked into the details of the other parts of Cairngorm besides Model Locator I’m not prepared to write off the framework completely just yet.”

    Translation:

    I realised that after having written 3000 words mostly about the Model Locator pattern this was not the article to go in to the details of the whole framework. I haven’t compiled my thoughts on the rest yet, but my general impression is that it’s more of the same, more global variables, more programming to concrete implementations, etc. However, I’m open to the possibility that when I delve into the details there will be subtle elegance. Nothing I’ve seen so far suggest that there might, but there’s a chance.

  17. Robin Hilliard Says:

    > I agree that the ModelLocator is one of the weak points of Cairngorm when compared, for example, with PureMVC – though my reasons are not exactly the same as yours:

    Hi Jim – in practise on a large Cairngorm project breaking up the models wasn’t hard. It was basically along the lines of what functionality had the potential to be reused separately in future. We were able to break the app up into mini apps and even build a FlashLite 2.0 application (it was all AS 2.0 on that project) reusing models, commands, and delegates.

    > I also agree that the documentation for Cairngorm is very poor. The people who created the framework have not maintained up-to-date explanations or tutorials.

    They’re sort of busy running the Adobe EMEA consulting practise :-).

    > But I will go along with your idea that everyone should standardize on American spelling! :-)

    C’mon – the english-english speaking world create one framework, and you don’t let us spell things our way – and it’s standardiSe, please :-).

    And I’m not going to bother with this “I” debate except to say it wouldn’t influence my choice of framework. And it’s good enough for Eclipse.

    > Your two examples of when you think that marker interfaces could not be replaced can both be summed up by “because of laziness”

    I would call it “convenience” or maybe “pragmatism”. I apologise for defiling your post with these horrible words.

    > if you don’t trust your users to add metadata, how could you trust them to implement an interface?

    Well you cant. But one is less typing. And we also get an easy to find source file to write our comments in to explain what the implementations of the interface are intended to do (how do you do that with metadata then)? Don’t get me wrong, I’m a big fan of metadata, see:

    http://www.webdu.com.au/go/session/code-know-thyself-using-actionscript-metadata

    but I don’t see it being that superior to interfaces for this purpose.

    > The challenge still stands.

    Ok, you must have won then (lazy response).

    > However, having the luxury to choose, I will not bother with Cairngorm because from what I can tell from the information available it’s not worth the effort.

    There is a lot of dud information out there but in my travels so far it isn’t limited to Cairngorm or even Flex. On your criteria you are going to have trouble selecting any of the existing frameworks – for example PureMVC has five singletons (which you access through a single Facade, yes – if it bothered you you could easily add your own Facade class to a Cairngorm app – we actually used a Code-Behind super class of our Application for this stuff) and uses the “I” prefix on commands.

    There are some things I disagree with in Cairngorm (chained commands, typed accessors in the ServiceLocator and naming it after a hard to pronounce Scottish mountain, forsooks) but my response is not to immediately run off and write my own Kosciusko framework.

    > I’m not criticising your use of Cairngorm, but the use of Cairngorm as it is explained, promoted and exemplified in the available documentation and example applications.

    Fair enough, I’m on the record (at the end of that video) saying that no demo app will ever convince you to use a framework. As for documentation, I’ve had a task in my list to write a small Cairngorm whitepaper for a while, maybe I’ll get to it eventually.

    Robin

  18. zwetan Says:

    Theo, about the “I” convention for interfaces

    first I used that because I was coding in .NET/C# and that was the convention, then Adobe used it as a convention, and later as I said before I kept using to show that class should be use as a template to do a particular implementation.

    Here a concrete exemple, I’m working on a small framework that gonna implement maybe 3 or 4 different serializers/deserializers, for one I want all the different serializers to have the same interface, for two I want to allow people who would want to add their own serializer to have a clean way to do it and for such just implement the interface. (ex: http://code.google.com/p/maashaack/source/browse/trunk/ES4a/src/system/ISerializer.as )

    But to me that interface ISerializer, I don’t see it as a type at all, hence why I use the the “I” convention to signify “template”, “behaviour”, “structure-to-follow”, etc.

    And to go on for the example sake, in this framework I got also a ISerializable interface, yep for this one I would totally agree to refactor the name to Serializable and ditch the “I” convention.

    hope that make sens ;).

  19. Theo Says:

    Zwetan, I think your explanation makes sense. I belive I understand what you mean by the interface being more a template than a type, and in that case by all means prefix it with “I” (although I might disagree with the clarity of using “I”, but that is a matter of preference).

    However, I’m not really sure I agree that the example you give (ISerializer) isn’t a type, but that might depend on how it’s used. If it’s not visible outside the framework, then fine, but if it’s the abstract interface of serializers, then I really think that it describes an abstract type, and shouldn’t be set apart by its name.

  20. Jim Robson Says:

    Robin – I appreciate your perspective on breaking up the model, and I’ll definitely give that some thought.

    My remark about the Adobe Consulting guys was not intended as a criticism, merely an observation on the state of things as they are. I’m sure they’re busy.

    And OK – in honoUr of my Scottish and Irish forebears, I’ll vote that we keep the UK spelling in Cairngorm. It’s a learning curve for the typical American to spell (or pronounce) Cairngorm, anyway, so we may as well learn to initialiSeCommands while we’re at it. :-)

  21. Theo Says:

    For those of you who missed the point about the spelling issue: the problem isn’t that they spell it “initialise” as much as that they spell it differently from class to class. Naming should at least be consistent.

  22. Jim Robson Says:

    Theo – I did not miss your point about consistency in naming. In fact, I probably should have mentioned that I agree with you on that point; naming should remain consistent throughout any framework, as it should throughout any library, application, etc. But I couldn’t help having some fun with the American-vs.-British aspect of it. :-)

  23. Robert Cadena Says:

    Thanks for the article. I’ve come to some of the same conclusions as you.

    When developing tests for my application I had a hard time replacing the models and event the services in the service locator with mock equivalents.

    I too found it odd that my views were now dependent on a global class. This dependency became even more apparent when the application was split up into modules and 3rd party developers needed to have access to some of the models.

    I eventually ended up fixing many of these problems by following the approach you suggested: dependency injection. Whoever creates the view is responsible for setting its dependencies. This was a bit of a change since, in Flex, one is so used to just laying out components and hitting run. But it resulted in more manageable, explicit code, and an easier to modify structure that could be unit tested more easily.

  24. san Says:

    Hi, Interesting article. I have only developed a small project in Cairngorm so far and I have developed a big project without using CG before. Having done some work in both I am just presenting my own personal opinion on the benefits of using CG.

    The frontcontroller makes it very easy to find problem areas because it gives you like a “sitemap” of your app which helps you divide your code into sections and create/manage them more easily.

    The commands have been great because they’re like shortcuts to portions of your code. It also makes debugging easier because when all the logic is contained inside one class (“execute” function), you can quickly isolate that, and fix it.

    Value objects are nothing great but I guess there are programmers who would store their states in strings, numbers.. so that forces you to keep it neat.

    Views especially make it easy for apps that require login screens, etc. I do agree that it may not be viable for where there are views inside views. But when you have only one Viewstack I found it a good solution.

    Events also are great for debugging. Its very easy to log/trace which was the last fired event seq which caused the problem.

    With all that said I do find that it takes about twice the time to create apps in CG :/ So far, the investment in learning, using it has far exceeded the benefits.. but I’m guessing as my app progresses I’d see more pros/cons of it…

  25. Matt Law Says:

    Hi Everyone,

    Well as someone new to flex, new to cairngorm, this intellectual stand-off has left me feeling a bit confused.

    I knew that Cairngorm was a bit long winded, but I was open to the notion that the rigour would pay off with large scale applications, and now that seems to be up for debate.

    I did find the name and global nature of the modellocator slightly odd.

    Perhaps one of you could elaborate on these strategies for using cairngorm in large scale apps whilst avoiding one massive ModelLocator? Maybe post some example “extensions/modifications” to the cairngorm framework, citing how you’re implementation improves on the original?

    Many thanks.

  26. Theo Says:

    I think that there is one thing that most of the people commenting above could agree on (and Robin probably said it first): the most important thing is to keep something like MVC in mind whatever method you use to create the application, and that if you are not an experienced software architect then using an application framework is probably better than rolling your own (I say “something like MVC” because MVC doesn’t have a clear-cut definition and there are alternatives/variations like MVP, the point is to achieve reusablility and all that).

    Having said that, I don’t think that it’s a good idea to get started with Cairngorm if you have a choice, it’s better not to learn the bad lessons Cairngorm have to teach. I’ve been looking at Mate lately (you can find another post about it on this blog), and it seems like a good alternative, although it’s new and unproven so far.

  27. John "Z-Bo" Zabroski Says:

    i think my prev. post was swallowed by akismet for posting a link

  28. Theo Says:

    No, can’t find anything in the spam box, try posting again.

  29. John "Z-Bo" Zabroski Says:

    Basically, I said that it seems from the dialogue between you and Robin that Cairngorm’s ModelLocator strives to be like TheGlobalModel object used in the DrJava IDE. However, it fails. The link I posted was to Brian Stoler’s master thesis, which explains the use case driving the design. http://www.cs.rice.edu/~javaplt/papers/brian-ms-thesis.pdf See chapter 4.

    TheGlobalModel object is also covered in Eric Allen’s explanation of The Liar View bug pattern. Allen does a much better job describing the details.

    The point behind MVC is NOT to achieve reusability, though. This is the unfortunate viewpoint that all these incurable do-it-yourself framework creators have. The point is to separate concerns. Reusability emanates from the Producer / Consumer Model, because it defines how you view the application’s relationship with the service; thus, you can reuse the entire application ‘above’ the data layer.

    Come to that, nothing about MVC is reusable by default. In order to reuse something, you have to encapsulate, either with a pure function or an object (which is stateful by default, and therefore adds destructive assignment (explicit state) into your application model). To encapsulate, you need a variable, which implies two further concepts: an identifier and a store.

    The proliferation of ideas about what constitutes MVC creates ensuing confusion about what MVC actually is. At its kernel, MVC is an incomplete application model. It does not describe how to represent application state, it only defines where to put application state (in the Model). It does not define a model for encapsulation. If you read Stoler’s thesis, you’ll note that their use of reflection in DrJava forced an unusual model of encapsulation. Due to their use of stateful concurrency, they needed an encapsulation model designed to avoid livelock as well as to avoid security issues.

    The lesson to take away here is that design is about constraints. A framework imposes constraints. This is a trade-off first an foremost at the canvas level: instead of using a blank canvas for your blueprint, you are forced to take into account design parameters provided by business constraints and technology constraints.

    However, these constraints should be independent and therefore you should be able to address each constraint with a model in a kernel language. Doing so allows you to compose, not necessarily reuse. Constraints create context, which implies some degree of specialization. Specialized components are by definition less reusable than general components. What you really want to do is compose together unique constraints. If your design does not allow you to compose together specialized components, then you have an “unholy mess”: coupling between specialized components with independent concerns. This describes the ‘low cohesion’ idea, because there is no way to do ad-hoc association (‘high cohesion’).

    Anyway, enough ranting.

  30. Theo Says:

    I think I meant that reusability was a goal of object oriented design, not MVC in particular, but I see now that that is not what I actually said.

    Even so, I belive that MVC (or MVP, or whatever, see below), is a factor in creating reusable components when building applications. With loose coupling and separation of concerns you end up with a model that doesn’t depend on the controller or the view, and thus it is reusable for other applications that do something similar (you can find one use case in one of my comments above where I have build an application that is basically a subset of a larger application).

    Depending on how you design the rest of the application even parts of the view will be reusable. For example a login form will be reusable in any other application that has the need for a login form, but it will only be reusable if it doesn’t contain application specific logic, and by applying the ideas of MVC it won’t have.

    So yes, you are probably right in that reusability isn’t a core concern in MVC, but it is a consequence. Unless you do other things that limit the potential reusability, like tightly couple your views to a global variable.


    Re: The proliferation of ideas about what constitutes MVC creates ensuing confusion about what MVC actually is.

    Well, that depends on what you mean that MVC actually is. If you mean that it’s something specific, then you are part of the confusion-creation. “MVC” has had a few very specific meanings in different environments, see for example Martin Fowlers essay on GUI Architectures ( http://martinfowler.com/eaaDev/uiArchs.html ), but I would say that nowadays its meaning is vague because, as Fowler points out, many things have changed since the first few incarnations of the idea, and many of the problems that motivated its creation are no longer problems.

    I try to avoid using the term MVC because I don’t think it’s helpful (I didn’t mention it in the original post at all), it’s almost always used as if it was something very specific, but in reality it’s very vague.


    I glanced through the global model part of the thesis, and it sounds like DrJava uses more or less the same bastardized service locator idea that Cairngorm does. I don’t understand the connection to the Liar View though.

    Speaking of Liar View, I think there is one very good solution to the problem: Presentation Model ( http://martinfowler.com/eaaDev/PresentationModel.html ), it’s a nice way of making the view more testable, and avoid the problem of the Liar View. Paul Williams has written more specifically how to use Presentation Model in Flex: http://weblogs.macromedia.com/paulw/archives/2007/10/presentation_pa_3.html and how to use it to simplify testing of views: http://weblogs.macromedia.com/paulw/archives/2008/04/unit_testing_us_1.html .

  31. John "Z-Bo" Zabroski Says:

    The Liar View bug pattern term was coined by the DrJava project. TheGlobalModal object is not a bastardized idea. It is merely an interface to some SCID (Source Code In a Database). However, ‘merely’ is not a sufficient adjective to describe it, because the Big Picture for SCID is quite encompassing. Calling TheGlobalModal object a bastardized idea shows misunderstanding or unawareness of ‘security realms’ in database technology.

    So, what’s the big picture of SCID? Since most application developers cannot tell the difference between a database and an appliance that only requires plugging in, I’ll start there.

    In your typical non-subvertible DBMS, security is organized into a realms model. Typically, there are two major realms: server and database. A server realm is a container for one or more database realms. Although CRUD is performed in a database context, users must have separate privileges to access the server and database. Note that this is specifically privilege separation, not privilege escalation: Just because you have access to the server through valid credentials does not give you access to any databases. The database must recognize your credentials e.g. grant you access to itself.

    The remarkable aspect of relational databases is that they are complex systems that can describe themselves to the user, insofar as the user has privileges to the database-wide schema and cells that store the explicit state of the ‘instantaneous database’ the schema matches. If checking out (reading) the schema is ‘public’, then everything about the schema is accessible from the server realm. Traditionally, checking in (rewriting) the schema is ‘private’ and limited to the ‘dbo’ (database owner) or some surrogate user equivalent to the dbo, because the public should not be in control of the schema.

    Users of IDEs unknowingly interact with this realms model on a regular basis. Instead of the ‘server’ and ‘database’ concepts, they have ‘repository’, ‘solution’, and ‘project’. In the SCID model, all three of these are maintained by the IDE but manipulated by the user. A Continuous Integration server was a foreseeable concept in the context of SCID. Continuous Integration checks for code hygiene and data hygiene, just as a normalized database with sufficient integrity constraints ensures ‘The Enterprise Data Model’ is not ‘smashed’. Steve McConnell’s ‘Daily Build and Smoke Test’ strategy describes an early desire to bring the principle of non-subversion from the domain of discourse world into the application model world, and Continuous Integration moves to perfect it (but falls short). In any discipline, there is a correlation between having realms and preserving the sanctity of each realm (hygiene).

    What most people don’t realize about Continuous Integration is that not only does it help prevent ‘diverging or fragmented development efforts’, it also yields applications with growing functionality that consume more and more of the schema. With Service-Oriented Architectures, this consumption of the schema is now unbounded, because we’re not only consuming our Enterprise Data Model with Enterprise Resource Planning software, we’re consuming other organization’s Enterprise Data Model as well with Customer Relationship Management and Supply Chain Management software.

    The modern IDE’s compiler pipeline is an ever enhancing form of Continuous Integration, presenting live feedback and clearer diagnostics. It uses the Read-Eval-Print-Loop model in the most exotic way imaginable: through the traditional relational database method of computational reflection.

    But what are the schemas for an IDE? The programming language is the default assumption, but today it is an abstract tree of artifacts. It is not merely an Abstract Syntax Tree, it is an Abstract Artifact Tree.

    Being able to execute these abstract artifacts is one of the holy goals of modern software engineering e.g. executable UML. But don’t just agree; ask yourself, why?

    Probably the most important design pattern in Informatics is the instruction set architecture. Traditionally, it is the key interface that allows many hardware implementations to run identical software. Modern systems virtualize this concept: the CLR translates CIL (Common Intermediate Language) into a specific processor’s instruction set architecture. The CLR and similar execution engines are bringing the end to failed attempts at component-oriented programming like CORBA, and therefore technologies like COM and SOM. COM/SOM were both intended to allow the embedding of ‘active objects’ within an application. Replacing it with CIL Assemblies and Components returns us to taking advantage of the key interface provided by an instruction set architecture.

    The major difference is we’re giving birth to Reflective Application Models that use concepts like TheGlobalModel object, which provides a facade to execute user actions in an interpreted and secure-by-design manner. Doing so will wreak chaos on how we model encapsulation. Morever, we are consolidating command languages into pictorials and visual languages, because users naturally assume consistency and reason by analogy. What do you think a Dashboard is?

  32. John "Z-Bo" Zabroski Says:

    Let me make one last post before you scald me for sounding recluse. ;-)

    Perceived limitations are not the same thing as real limitations. Using a tool in a way unintended by its design leads to perceived limitations. In software, bitching about it is better than not bitching about it. Our bitching is a tool to educate future design. Using a tool has consequences, and we’re far better off reflecting on those consequences than falling into habits encouraged by the tools we use.

    Buck Showalter, a World Series winning manager, once asked a third base coach he was interviewing how well he did his job the previous season. The third base coach said, ‘I had a great year. Nobody I waived home got thrown out.’ Showalter told him, ‘No, you had a bad year. If you didn’t get at least one person thrown out, then you were afraid to win. As a manager, I want a third base coach who will steal runs for me.’ (paraphrased)

    Come to that, the biggest lesson I learned from your blog entry was that CG developers don’t care to document what those real limitations are, so that we may compare them with your real limitations.

  33. John "Z-Bo" Zabroski Says:

    er, so that we may compare them with your perceived limitations.

  34. Theo Says:

    I didn’t say it was a bastardized idea, but that it was a bastardized version of the service locator pattern. Bastardized because it sounds like it didn’t offer the decoupling that service locator does. This is the same problem as the service locators in Cairngorm (and it was you who made the suggestion that they had something in common), they make you couple your code tightly to them which is not the point of service locator, hence “bastardized”.

    I cannot understand what you are trying to say or prove with the rest of your comment. May I suggest that you start your own blog, or keep to the topic.

  35. Tech Per » Blog Archive » Patterns of GUI Architecture in Cairngorm and PureMVC Says:

    [...] post of Theo Hultberg shooting holes in Cairngorm ModelLocator (be sure to read the comments [...]

  36. When in Rome… « blorgitude Says:

    [...] I found the Architectural Atrocities blog series, which has quite a lot to say about Flex, and Cairngorm in particular (which is what [...]

  37. Romain Says:

    Intresting article. But, more intresting, comments and fights :)

  38. ryan Says:

    You provided so much criticism but not one solution? What gives?

    I agree that the documentation for cairngorm is old and actually hard to find so I can understand your frustration there, but have you considered actually contributing to the project?

    If you know so much about Cairngorm why not put that information into some of the documentation? PROVIDE A SOLUTION…

    I really think it’s lame to go off on a rant like this, is this the way you deal with technical problems that you can not figure out…

  39. Theo Says:

    @ryan

    So much criticism and no solution? Well, it depends on how you look at it. I don’t see the problem with pointing out the mistakes of others without explaining exactly what to do instead. I think there is value in just pointing out what is wrong with something, so that those that choose between options can weigh in the downsides of each.

    Besides, in this specific case the solution is pretty obvious: use another framework, there are others to choose from and I’ve written other things that explain what is good (and bad) with those.

    I don’t think that it’s up to me to explain to the Cairngorm team how they should do things, that is completely up to them. I do, however, think that I can criticise what they do and point out the flaws, in the interest of the community and in the interest of those who need to choose a framework to use.

  40. shaun smith » Blog Archive » Interactive Application Architecture Says:

    [...] http://blog.iconara.net/2008/04/13/architectural-atrocities-part-x-cairngorms-model-locator-pattern/ [...]

  41. Blog Xebia France - Revue de Presse Xebia Says:

    [...] de sa complexité, c’est ce qui ressort des commentaires. Peut être est ce à cause de son “ModelLocator fourre tout”. Les résultats sont intéressants mais il ne faut pas les prendre au pied de la lettre. Tous ces [...]

  42. andy Says:

    Wow, such a great article. I found it during a frustrated search for why the fuck we’ve got this thing named ModelLocator when it’s really just an interface for models… and really I agree with all of your comments except for the “I” for interfaces. I still think that’s a good thing. After all, your instance names aren’t being prefixed with an i. So you’ve got var scrub:IScrub… So what? That means with one extra letter new users suddenly can be confident that whoever wrote the code used interfaces. And everywhere else “scrub” is used there isn’t the “I”. So you’re getting a lot of value there. It’s a good thing. Switch sides.

  43. ryan Says:

    Hey Theo

    I have heard or seen this project: http://code.google.com/p/flex-slide/

    Key features:

    * Uses familiar design patterns
    * Robust MVC structure
    * View state management decoupled from view implementation
    * Flexible approach to model and controller access, eliminating need for singleton classes.
    * Separate view presentation from view functionality
    * Incorporated debugging and development tools 
    

    It works quite well and is flexible enough to use with cairngorm. So you can keep the cairngorm front controller and commands but scratch your singleton model and replace it with the slide framework.

    I thought I would drop by and make mention of it…

    I do appologies if I came off a bit too harsh there, but after reading such a long blog post I was expecting the golden answer at the end… alas… cairngorm has not been updated for ages and is quickly loosing faith amongst many in the community. I guess your criticism of cairngorm is an indication of what many percieve the framework to be.

  44. Theo Says:

    @ryan

    “I was expecting the golden answer at the end”

    If there’d been one I would have mentioned it at the top.

    I’m not out to solve all the world’s problems, but to make a point about software architecture — and in this case: how not to design an application framework. I don’t understand the notion that you can’t criticise things unless you have a complete alternative solution. The architecture of Cairngorm is laughable, why shouldn’t I point this out? I believe that you can learn just as much, if not more, by looking at the mistakes of others.


    I have glanced briefly at Flex Slide some months ago, and I’m not impressed by the big words. The statement “robust MVC structure” is almost completely devoid of meaning, the other bullets are similar. Mind you, the idea isn’t bad at all, but the presentation is hot air.

    It’s a state management framework, and I think state management is a hard problem. However, I’m not sure that all there is to it’s solution is to mimic the web. In fact, I think that the very problem with the web is that request URI:s don’t convey enough information — moving that thinking into RIA:s seems counter-intuitive to me.

  45. Romain Says:

    I finnally used PureMVC for the companie’s project. I must admit it’s great to use. It was a bit more tricky to get into it first, Cairngorm seems easier for me to undestand. But PureMVC seems more flexible for my needs.

    And their documentation and exemples are just great.

    +1 for PureMVC!

  46. ryan Says:

    The architecture of Cairngorm is laughable, why shouldn’t I point this out?

    Actually I think it’s great that you did point this out.

    But can you throw a dog a bone?

    I bet everyone is thinking geez which framework should i use, and will i ever find another use case for my dear old singltons (probably not but we all feel really bad for using them now)?

    What framework are you using then?

  47. Theo Says:

    I bet everyone is thinking geez which framework should i use

    They probably do. But I’m not sure it would help that if I said “look, Cairngorm is rubbish, you should all use X instead”, because if you can’t see that Cairngorm is a collection of anti-patterns, how would you know that X is better?

    However, I can see the point that without also knowing why other frameworks are better you can’t get to the point where you could actually make an informed decision for yourself.

    You can find a few things I’ve written on the subject at Stack Overflow:

    http://stackoverflow.com/questions/37043/flex-mvc-frameworks#37566 http://stackoverflow.com/questions/108889/objectively-what-are-the-pros-and-cons-of-cairngorm-over-puremvc#109038

    You can also find a few things I’ve written about the more general subject of how think about software architecture in Flex here:

    http://code.google.com/p/mate-examples/wiki/DocumentBasedExampleIntro http://mate.asfusion.com/forums/topic.php?id=252 http://mate.asfusion.com/forums/topic.php?id=217 http://mate.asfusion.com/forums/topic.php?id=177 http://mate.asfusion.com/forums/topic.php?id=172 http://mate.asfusion.com/forums/topic.php?id=203

    From the last few links you may have deduced my application framework of choice. To me it’s not a religious issue; I’m using Mate because the alternatives are, frankly, really bad. I’ve outlined some of the problems of the major Flex application frameworks in the Stack Overflow posts linked to above, so I won’t repeat them here — but suffice to say that for me the choice is not a hard one. I don’t mean to say that I use Mate because it was the least bad, I really do like it and very much prefer it over writing something myself, but I also don’t think that there is any competition. The issues I have with most other Flex application frameworks I’ve looked at (and I try to keep up) are at a fundamental level, they are not details and not something that can easily be fixed.

  48. ryan Says:

    http://stackoverflow.com/questions/108889/objectively-what-are-the-pros-and-cons-of-cairngorm-over-puremvc#109038

    i honestly can say it really is the most objective review of the various frameworks available to flex developers.

    you convinced me…

  49. Architectural Atrocities, part 10: Cairngorm’s Service Locator / Iconara Says:

    [...] The last post stirred up quite some debate and I’d like to thank everyone who commented on the post. I’m amazed that people still post comments (by coincidence to the day) seven months later. [...]

  50. Jack9 Says:

    What’s in a name?

    Name decoration is not required, nor is it bad for any reason other than it peeves you. I bet you seeth over curly brace placement. Get over it.

  51. Theo Says:

    @Jack9 you miss the point. It’s not that I find interface names beginning with “I” ugly, it’s that I believe that if you name them that way you don’t know what they are for.

  52. Newton Says:

    Hi, I am not a regular user of CG yet..I used to keep my code very simple by using simple design patterns. I just looked in to their classes & interfaces as well as the example files.. To some extent I am with you( when you mention about the ModelLocator). I really not in support of making the model to be a singleton. But some times it’s helpful & I am happy with the results rather than caring about using an anti-pattern. BTW, you have put some strong logic-quite appreciable

  53. martzobg Says:

    I think cairngorm side by side with spring as sounds like a pretty good solution. What do you think? ;)

  54. Iconara » Quoted in “Professional Cairngorm” Says:

    [...] in a book with the (contradictory) title Professional Cairngorm. It’s the now (in)famous Architectural Atrocities 9: Cairngorm’s Model Locator Pattern again. It’s not the best quote to take from that post, but beggars can’t be [...]

  55. Learning Cairngorm 3, Part III: Some fiddling, some architecture « journeysinflexland Says:

    [...] 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 [...]

  56. Flex MVC Frameworks « « Programmers Goodies Programmers Goodies Says:

    [...] that are tightly coupled to global variables. Nuff said (but if you’re interested, here are some more of my thoughts, and here [...]

Leave a Reply