Code Behind is a somewhat vague term that means different things to different people. I believe it was originally coined by Microsoft to describe any strategy for separating logic from content in ASP pages. Using this broad definition it could be argued that the Supervising Presenter, Presentation Model and even the View Helper are all examples of the technique. So this interpretation of code-behind lacks the sort of precision we require to discuss it as a pattern.

However, one of the most common methods for achieving code-behind in ASP and .NET uses inheritance: Presentation logic is extracted out of the view class, and into the view’s superclass. The technique has been brought over to the Flex world and is arguably one of the most talked-about and advocated presentation patterns. It is this "code-behind pattern" that I am going to look at today.

Key features

  • Logic (and other "developer" stuff) is in an ActionScript superclass
  • Layout (and other "designer" stuff) is in an MXML subclass


Language Segregation

I think the primary motivation for the Code Behind pattern is the segregation of ActionScript from MXML in order to support a developer/designer workflow. The precise division of responsibilities between ActionScript and MXML varies across implementations. Event handler specifications are usually extracted into the ActionScript class, but there seems to be some difference of opinion on whether binding statements can remain in MXML. It is also unclear whether designers can be expected to configure declarative validation in the MXML file. In my example I have extracted event handlers, binding statements and validation into the code-behind class.

Unit Testing

I’ve not seen much discussion of unit testing Code Behind classes, but I suspect they may be more ‘testable’ than equivalent Autonomous Views.

Code-behind classes contain references to sub-views; so unit testing them is likely to require mock objects. Since instances of sub-views are instantiated by the MXML subclass, it will be necessary to find a way to inject suitable mock instances when unit testing the base-class.

In addition to having references to sub-views, code-behind classes also contain references to UI controls. Since Flex controls do not implement interfaces, it is unclear to me how they could be mocked in the traditional sense. I think further investigation is required to understand the issues here.


Why extract superclass?

With the exception of the Autonomous View pattern, all of the patterns I’ve looked at so far attempt to extract logic from view classes into a separate set of ActionScript classes. This kind of refactoring is often referred to as ‘extract class’. The Code Behind pattern is unique in that it attempts to extract logic into a superclass, a variety of refactoring known (somewhat unsurprisingly) as ‘extract superclass’. Generally speaking the extract superclass refactoring is applied to move functionality shared by two classes into a base class in order to reduce code duplication. But in the case of Code Behind, we only have one view class. So why use extract superclass?

Poor separation of concerns

By performing an extract superclass refactoring, the resulting ActionScript class is still very likely to extend one of the Flex framework components such as HBox, VBox, or Panel. So it is difficult to see any real separation of concerns. As with the Autonomous View pattern, the layout concern is still central to the class hierarchy and code-behind classes are unlikely to have a common editable base class.

Tight coupling

The two classes resulting from the code behind pattern are very tightly coupled. An inheritance relationship is arguably the most intimate of associations. In advanced architectures it may be desirable to have more than one logic class for each view (for example to provide different view behaviour for different user roles); this isn’t possible when the view extends the logic class.

Is MXML only for designers?

Perhaps I’m being selfish, but there are two very useful features of Flex that are only available in MXML:

  • Bindings with curly braces ‘{}’
  • Declarative event handlers

Whilst I could probably live without these two features, I’d prefer not to.

Example application

The example application demonstrates the Code Behind pattern; right-click to access the source.

Final thoughts

It isn’t clear to me why the Code Behind pattern favours inheritance over composition, and I think this is the main drawback to the approach. Although logic is extracted out of the view, the resulting code-behind class is still tightly coupled to the Flex framework. Furthermore by having the view extend the code-behind class, the view becomes very tightly coupled to the logic.

By favouring composition over inheritance, the Supervising Presenter and Presentation Model patterns offer improved separation of concerns and consequently greater flexibility. Neither of these patterns achieves the same degree of separation between MXML and ActionScript as the Code Behind pattern, but the next pattern I’m going to look at certainly does. It’s another one of Martin Fowler’s and it’s called Passive View.

9 comments so far

Add Your Comment
  1. As you mentioned above, using inheritance fails to seperate logic from view as the logic class needs to extend the required view component. It also has the downfall of not being able to declare logic that is access by the view as private.

    I prefer the use of the Scrit tag and specifiying an .as file as the source. your logic now know nothing about the view at all, instead the view binds to values in the logic, and calls methods on it.

  2. Thanks for the comment, I remember reading your own blog entry on code behind when I was researching this post.

    Feel free to correct me, but I think regardless of whether you

    a) Put logic directly in your MXML class

    or B) Use the source attribute and break the logic out into a separate file

    you’re still following the AutonomousView pattern. The physical separation of code across two files does not have any impact on the architecture. There is still only one class (the view class). The ActionScript file cannot be described as a class or a partial class because it contains no class declaration.

    I’d be interested to know more about the motivations for this approach. What does it help you achieve? Does it have any drawbacks?

  3. The motivation is really just to keep the view clean, i.e. it doesn’t contain a script tag with a load of AS in it. It also makes the logic portable, i.e. you could have a few different ScrollBar views all using the same scollBar.as logic. There is only one class though as the external AS just get injected into the class at compile time. It also enabled the dev working on the view to decide what base view class they want to extend, unlike the inheritance method where the base view class has to be specified in the logic.

    One of the drawbacks is that you don’t have a reference to any of the objects in the view, unlike the inheritance method, where most people seem to define all their view items in their logic class so they can reference them. If you did this with an external .as file it would show and error stating you have duplicate definitions. This isn’t a problem though if you don’t reference an view in your logic, instead binding you view to values in your logic.

  4. It sounds like your approach has some similarities with the Presentation Model that I discussed earlier, except you do not create your model as a separate class.

    Thanks for taking the time to comment, its great to hear other people’s thoughts on this subject.

  5. I have been looking into a development pattern that can be easily applied to our very large, very complex business applications. These apps need to integrate complex business rules that ripple throughout the entire app view. On top of that, these apps are being constructed by a team of developers in Boston, Ireland and India - all who have varying degrees of expertise, and where the sudden turnover of staff is a prime consideration.

    To date, the best approach has been to stipulate that ‘no actionscript reside in the view’. That is - *.mxml contains only mxml tags. Except for two things 1): the import of that templates viewHelper (presentation logic), and 2) registering {this} with an ‘abstract’ view which contains strongly typed static instances of that mxml class (creationComplete=AbstractView.foo = this).

    Thus any component that needs to call a static function calls it in this manner: ‘click=ViewHelper.doClick(event)’
    And all the functions used by this mxml template, as well as all the components in that template are accessible from all corners of the app. It works like a charm; the developers have the option of ‘registering’ the mxml template; it keeps all presentation logic separate from the view; allows easy refactoring and debugging (read: maintenance); is easy for (encourages) the developers to comment code; dovetails perfectly with the model (singleton); and the project chugs along despite situations of sudden turnover. Just curious … anyone else take this approach?

  6. Hi Mike, thanks for posting this, I have a few questions:

    Are your view helpers following the ViewHelper pattern I discussed a couple of weeks ago?

    Is the ‘abstract’ view acting as a kind of view locator?

    Finally, what problems are you aiming to address with this approach, and are there any drawbacks?

  7. Hi Tink,

    Good idea with the source tag. However, my question is how can you make the code located from the Script source parameter not know about the MXML?

    When I reference an .as file with code (note, no class definition in here as that doesn’t seem to be possible with source) from the mx:Script’s source parameter I can reference the MXML with using “this” the same way if I would use an include statement or code within mx:Script.


  8. I also posted this on Best Practice: Code Behind versus MXML Script Blocks versus View Helper

    Coming from the .Net world I am all too familiar with the code behind and its magnetic ability to make developers place business logic inside it. The flaw is not with the pattern but with the way it is used.

    For example I am in the middle of a MVC application using the core of Cairngorm but with out the anti patterns. Each of our views has a code behind but it is purely for wiring up event handlers and any custom display rendering. IMO this does not remove the need for ViewHelpers but it provides a nice place to call the view helpers from without cluttering up the design view.

    So again to reiterate my point, it is not the CodeBehind that should be discarded, it is the lazy developer who cannot be bothered to call back to the business logic.

    My 2 cents,

    Bro Num

  9. I’m a Microsoft developer primarily by trade and one of the nice things about developing asp.net is that the IDE - (Visual Studio) does all the hard work of seperating the view from the “code-behind” for you.

    Initially I started out creating code-behind pages in Flex but gave up due to the sheer effort to do so. For example to work well, your code-behind should be aware of what objects are declared within your mxml file and what their id’s are. You can then use these id’s within code-behind with all the usual hinting - perfect.

    If Flex builder were capable of creating a partial class file for your code behind - and that partial class were updated for you absolutely do code-behind. Othersise its a huge pain in the ass.

    So FlexBuilder wish list:
    1) Partial class definitions (not inherited classes) for code-behind action script files that are tied to an MXML file within the IDE ( Live VS 2005 etc)
    2) Automatic updates of the available objects and their id’s in the code-behind file - when placed within the MXML file (or edited or removed for that matter)
    3) Automatic generation of event handlers from the mxml MXML objects when double clicked in the IDE ( or control clicked or something )