Archive for the ‘Design patterns’ Category

Passing on objects through constructor

March 20, 2011

I am reading this nice article about architecting your application using Model View Presenter. In the application where you have lots of parts that work together and share some of the plumbings, the way you pass those plumbings around is that you have some centralized objects that are responsible for instantiating both the shared objects and those parts and you pass on the former to the latter  through their constructors:

// A part that asks for the infrastructure such as RPC service, event bus, etc..

public ContactsPresenter(ContactsServiceAsync rpcService,
HandlerManager eventBus, ContactsView<ContactDetails> view,
List<ColumnDefinition<ContactDetails>> columnDefinitions)


// The application controller, which constructs most of the parts that do the work.

public AppController(ContactsServiceAsync rpcService,
HandlerManager eventBus) {
this.eventBus = eventBus;
this.rpcService = rpcService;

// GWT's bootstrap process calls this "Main" that sets things in motion

public class Contacts implements EntryPoint {
public void onModuleLoad() {
ContactsServiceAsync rpcService = GWT.create(ContactsService.class);
HandlerManager eventBus = new HandlerManager(null);
AppController appViewer = new AppController(rpcService, eventBus);

The point is that a working bee (such as the ContactsPresenter) only needs to know the minimal (what he needs to know in order to get his work done). If he needs an rpcService, he does so by simply asking for a rpcService object in their constructors, or maybe have a setter property that can be used by a controller to assign a rpcService to it; but they should not set the rpcService object by themselves, like this:

// an anti-pattern ContactsPresenter object:
this.rpcService = ModelLocator.instance.rpcService;

Think about the scenario when the rpcService object later is to be moved to somewhere else; then we would have to change the code in all the working bees that use this rpcService. If we set the rpcService object through some centralized place (such as in module loader and appController), we would only need to change those few places. Another bad thing about doing so it that then your working bees start to know about too many details (like they know that the rpcService stores in the model locator singleton, which might change later on.) and start to dependent on those assumptions/details.  These couplings make change harder.

A better approach would be to inject those information from outside, such as managed by a few centralized objects, as we did from the beginning.

I think the real world analogy is that a working bee is expected to simply get the work done and not beyond. If he needs something, he would ask his manager, “I need a truck”. It’s the manager’s job to assign him a truck instead of him going out and looking for a truck by himself. (Or maybe not.)

P.S., Later I found out that a more trendy way of saying “to pass on objects” is “to inject the objects”. So the title of this post can then be rephrased as “constructor injection”.

MVVM: Take One

June 26, 2010

I am wrapping my head around MVVM (Model-View-ViewModel) these days. Although I am a totally newbie to .NET, I’ve found it a very good thing to relate it to my experience with Flex SDK, as it gives me a deeper understanding about the thinking behind UI development. John Gossman from Microsoft has an awesome article about “MVVM“; Paul Williams from Adobe also has an awesome article about “Presentation Model“. Here is Martin Fowler’s article about “Presentation Model” that Paul refers to.

“ViewModel could be seen as a specialized aspect of what would be a Controller (in the MVC pattern) that acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model. The ViewModel exposes public properties, commands, and abstractions. The ViewModel has been likened to a conceptual state of the data as opposed to the real state of the data in the Model.” Basically ViewModel is a specialized representation of Model that is designed to manipulate View in a way that’s more friendly to the user mental model of the data (or in another word, how the UI is presented). Changes in the properties of ViewModel and changes in View are coordinated via data binding, mostly conveniently done declaratively.  These kind of “out-of-the-box” plumbings of Flex and WPF have freed the developers from having to deal with lower level of View manipulation using code, instead help them to focus on thinking in terms of user mental model, application flow and user interaction. There is this statement that ViewModel and View are completely decoupled, which I don’t agree. ViewModel is an adapter from the Model to the View; If the UI or user flow changes, the ViewModel has to change accordingly. Say you are building a “shopping cart” app for books that’s used on a small screen device. Users chooses “language”, “genre”, “year” and then “prices” consecutively which leads to a result of matching books (or no matches). You may use a ViewStack to display the options at each stage so that only one set of menu is presented to the user at a time. In your ViewModel, you may have the following:

public static CRITERION_LAN_SET:int = 0;
public static CRITERION_GENRE_SET:int = 1;
public static CRITERION_YEAR_SET:int = 2;
public static CRITERION_PRICES_SET:int = 3;
[Binding] public var selected_criterion:int;

/**Hook to a “Next” button or an item in each of the aforementioned selection menu so that when the user taps on it, the ViewStack can advance to the next menu */
[Binding] public function addToSelectedCriteria():void
if(selected_criterion < CRITERION_PRICES_SET) selected_criterion++;
<mx:ViewStack selectedIndex=”viewModel.selected_criterion”…/>

So if you decide to have a desktop version that can present all the selection criteria at a time as opposed to one by one, you will then no longer need addToSelectedCriteria() or selected_criterion in the ViewModel.

Data binding is an adapter in declarative UI programming which enables developers to program in higher level when dealing with user interaction. Without the plumbings provided by data bindings and commands, etc., you would need to manage UI states directly with “code” that manipulates the View — but you would probably prefer to delegate this kind of lower level manipulation to more specialized objects, as opposed to dealing it directly with your ViewModel — while with Flex and WPF, you delegate these tasks to the framework.

In conclusion, the whole point of all these fancy patterns still nails down to the very basic stuff about programming, things such as breaking down different levels of tasks into different layers and chunks of code, such that your code maintain a hierarchical structure in terms of abstractions (called “decomposition” or “stepwise refinement”). This results code easy to understand, maintain and modify. It’s worth pointing out as we step back for a moment to take a breath and look at a bigger picture.

MVC revisit: Take two

June 7, 2009

I find that MVC is much easier to understand both at the conceptual level and at the implementation level if you think about it from the perspective of how you communicate with the Model.

  1. Control is the input to Model. Basically, the Control is responsible to take input from the user or the system and stransfer it to the changes in the Model; The View is merely there to render the changes from the Model; so it can be considered as the output from the Model. You should keep the business logic as much as possible inside the Model and leave Control/View simple and dandy.For Flex 3 (Halo) components, the way of input is realized by implimenting the “change” listener of the controls, like this:

    <mx:TextInput id="mTxt" change="mVO.txtValue = mTxt.htmlText;"/>

    In Flex 3, when you bind a model to a control, it is one-way communication, meaning the control will reflect the change whenever there is one in the model; but the control would not be able to change the model. That’s why we need to wire through the change listener to make this happen.

    The output is hooked up by setter methods in the Model. Whenever you detect some changes that are historical, you would notify your listeners.

    public function set myValue(v:int):void
    myValue = v;

    In ActionScript 3, we normally implement “notifyListeners” by way of dispatchEvent. Your client listens to the event and updates the View by querying the changes from the Model. You may want to have different types of events so that your listeners can respond differently. For example, you normally would invalidate properties of your component and regenerate all the renderers when the data provider has changed, besides doing other updates; and you don’t want to do this kind of heavy-lifting each time when changes occur on the “less important” members of the Model.

  2. Asynchronous data. Sometimes you may compose something like an HTTPService component into your Model so that it can request external data.The data that are requested by the Control at a lot of times are not immediately available, and normally you would not notify your listeners until they are ready (For example, parsed into an XMLList object that can be consumed by component’s dataProvider).
  3. Static members are available before non-static members of the objects. You can use static members to set some initial values of your member variables.
  4. When you smell spaghetti code in your Model, try to partition/refactor your Model into smaller Value Objects. Value objects are a good way to structure your data/make flat Model hierarchical.
  5. For larger projects, you may want to duplicate Model (or value objects) so that multiple client can access the same data. For example, in your main window of your AIR application, you initialize your model like so:

    public var chatModel:ChatModel = new ChatModel();In another console window, you want to access the same model, like so:

    private var chatModel:ChatModel = Application.application.chatModel;

datagrid local pagination in flex

April 18, 2009


We use a local data provider (a collection) which is a reference to the real/remote data filtered by filterFunction (clamped by the index range of the requested page).

Cairngorm 101: Take one

March 28, 2009

Here is how things are set up in Cairngorm v2.2, based on what I learned this morning through this series of step-by-step tutorials (text accompanied by videos):

  • The members in views are bound to the model locator using Flex binding. This is the foundation of the whole mechanism, which ensures whenever the model is changed, the corresponding views get updated. Flex uses [Bindable] meta data tags for binding properties and setters.
    Note that there are situations where bindings cannot be used or you prefer not to use bindings. For example, properties of the main application is not binable, which means you cannot bind width/height property of your WindowedApplication to some properties of your model locator. All the code inside a [Bindable] setter is lazy execution (meaning if you are trying to assigned the same value using the setter, nothing will happen).
  • You will also need to declare and instantiate the Control in your Main application, either by ActionScript or by MXML, in order for the whole thing to be set in motion.
  • The following shows how different parts are chained up in the Cairngorm flow to react to a user gesture. Note this flow doesn’t include a detailed view about how Model delegates to the business logic (residing largely on servers):
    View->Event->Front Control->Command->Model->View
    (here is a much nicer looking diagram from the original site)
  • ModelLocator is a singleton class that contains all the model/data classes plus the states of the models (such as “login”, “checkout”, “view in thumbnail”, “view in grid”, etc..) Again, in Cairngorm, the model updates views by utilizing the Flex binding mechanism.
  • Model classes (TODO)
  • Business delegate classes (TODO)
  • Command is the worker class who does the heavy lifting. Usually, it knows the business logic and carries the underlying algorithms. In your code, there should be defined separation of labor among Command objects and each Command should only concentrate on one thing. Each command object is associated with a a typed Cairngorm Event, which is passed down from the Front Controller. All Command objects carry out their duties by responding to a centralized Front Controller instead of directly to a user request.
  • Then how does a user request get satisfied? In Cairngorm, all the hooks between user gestures and their corresponding workers are done by the Front Controller. Front Controller is the manager class that keeps the list of commands for your application and keeps track of which command responds to which user guestures (presented as CairngormEvent objects). At the time an event is dispatched, it invokes the excute() method on that command and passes the typed Cairngorm event object which contains information about the specific user gesture that the Command object expects. The philosophy for Command/Cairngorm Event/Front Controller is similar to that of  Mediator Pattern: Encapsulating all the worker objects’ communication by decoupling the explicit dependency of objects on one another.:)

Here is how I approach the code flow, which for now I feel easier to follow:

  1. Create ModelLocator. This includes adding related model/data and “states”. This is like blocking of your drawing. After this, we can drill down into the details:
  2. Create VO;
  3. Layout View (UI control);
  4. Define event for the control;
  5. Create command to handle event. The command is the control in the MVC pattern, it interprets an user gesture and modifies the model ;
  6. Add the command to the Front Controller. This is like in your drawing when you are happy with the details, you step back again to adjust the relations of different parts ;
  7. Add Front Controller to the Main application if you haven’t done so,
    Add view/UI controls to the Main application if you haven’t done so;
  8. Go back to #3 > #6 to add more features.

“Effects in response to user input”

March 18, 2009

From” Joy of Flex“, buzzword UI/eye candy guru David Coletta.

Flex pattern: data renderer has to know about data

February 24, 2009

Halo framework provides a lot of out-of-shelf control classes that perform layout tasks, such as DataGrid and Tree. What they do is instantiating renderers based on their data provider and layout the renderers according to their own rules. In the Model/View architecture, these layout managers represent the view and the data provider object represents the model. Inside the trench, all the data renderers implement mx.core.IDataRenderer which requires them to have setter/getter for their data member.

The data setter method is the place where we hook up the renderer with its data; you normally also invalidate the component and/or fire events here when necessary. This also means unluckily we cannot stick in any kind of dataprovider and any kind of data renderers into the creator component and expect the latter to “automagically” hook up the data with the renderers. All the creator component do (and should be doing but not more) is to hook up data item with the individual renderer:

var renderer:UIComponent = _itemRendererFactory.newInstance();
IDataRenderer(renderer).data = _items[i];
renderers[i] = renderer;

It’s individual renderer’s job to decide on how he wants to render the data and the hook is the data setter method. The following code shows how mx.controls.Button implements data interface.

private var _data:Object;


*  The <code>data</code> property lets you pass a value
*  to the component when you use it as an item renderer or item editor.
*  You typically use data binding to bind a field of the <code>data</code>
*  property to a property of this component.
*  ……
public function get data():Object
return _data;

*  @private
public function set data(value:Object):void
_data = value;

//render the data we get
//dispatch the event
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));

So one data renderer would require certain format of dataprovider which may be different than that for another type of renderer. A real world analog is the manager only handles a piece of work to an individual and it’s up to that individual to decide how to process it, which is not the concern of the manager since the manager knows every little about the work itself; what the manager does is to choreograph the whole effort (setting-up, dividing, hooking up, coordinating, etc. of the data renderers) as a team. (Sort of 1 foot view vs. 5,000 feet view;) It’s kinda hard to get the same level of detail at different distances.)

The bottom line is, the renderer has to know about the data in order to render them. Yeah, common sense…

Flex pattern: Set property name or type at run-time

February 19, 2009

Scenario: I felt confused/embarrassed when the Starbucks barista asked me “What kind of milk?” when I asked for a “Misto“. Me, standing rolling my eyes, with a few thoughts quickly spinning around/above my head: doesn’t all the milk look same here? Do they also put soy milk in the coffee? Or maybe they have black milk here? I couldn’t figure out what my options would be after 2 seconds. So I probed: “What kind of milk do you offer?:D” She kindly replied: “1%, 2%, skim, etc..”

I guess the barista was expecting some basic knowlege which I obviously didn’t acquire by culture. (Oh yeah she is from the coffee culture and me from the tea culture for a side note.)

Let’s go back to our pattern thread. As developers of components, we want to apply loose coupling philosophy to our component architecture. Sometimes classes need to obtain their values from other objects rather than through locally set values and type selectors.

  1. Sometimes we’d like to have the developer determine certain aspects of our components (with these aspects esp. being states or styles of our components). Flex pattern: If you are creating components that are creator and manager of the data renderers, and your component are altering the renderers states by expecting them to “have” certain states, instead of hard code those state names locally into your data renderers, expose sub component state values as styles of the creator object and let the developer set them at runtime.

    var stateProperty:String = getStyle("stateProperty");//currentState
    var rolloverState:String = getStyle("rolloverValue");
    renderers[i][stateProperty] = (i == selectedItemIndex)? selectedState:
    (i==hilightedItemIndex)? rolloverState:unselectedValue;

    One thing attempting to do when you write your own custom component is to dictate the states of your descendant components  in the ancestor component (e.g. the creator of item renderers intrudes into the framework of the itemRenderers).  As in the following code, the component developer requires (sort of, since it recovers by using NaN;)) that the renderer implement “selectedStates”. Doesn’t look very elegant.

    //Code in
    override protected function commitProperties():void
    /**it’s often the case that a component will have more information its item renderers might be interested in than just the data.  It’s the practice in Flex to define a separate interface to allow define the additional information your component might pass to an item renderer.  Try not to require that your item renderers implement this interface…it’s nice to provide customers with the option to invest less effort but still get a gracefully degrading experience.
    in this case, we think our item renderers might want to render differently based on whether they’re selected or not.  While in controlled situations, you could just explicitly set the ‘currentState’ property of your renderers, If you want to allow developers to swap in different item renderers, that’s not a great idea. It essentially hijacks the view states of the item renderer, and doesn’t allow the developer to add additional states or behavior.  Better to let them manage their own currentState.*/
    if (inst is IRandomWalkRenderer)
    IRandomWalkRenderer(inst).selectedState = (isNaN(selectedIndex)?  NaN:
    (selectedIndex == j)?     1:

    With this being said, since our component _is_ interested in the states other than just data of the renderers, how do we let them know when we want them to change states? One thing we can do this more elegantly (or, hmm, “unobtrusively”) is to not to hard code the values of the states into our component since we don’t know what states the developers already have had in his plate and we don’t want to force the developers to implement those states as we require. But what we can do (tactfully;-)), is to expose our options (done by public members and styles in Flex) for these states and have the developers make their decisions of their own at run-time, just as the nice brista lady showed me what options I would have for the milk in my coffee. Of course the developer may completely ignore these options, which would require us to handle the situation gracefully, as mentioned as “degrading experience” by Ely in his RandomWalk component.

    Here is how Ely did it in his FishEye component :

    //snippets of code in
    * update the state properties of all of the items, based on
    * the current hilighted and/or selected items
    private function updateState():void
    var stateProperty:String = getStyle(“stateProperty”);
    if(stateProperty != null)
    var rolloverState:String = getStyle(“rolloverValue”);
    var selectedState:String = getStyle(“selectedValue”);
    var unselectedValue:String = getStyle(“unselectedValue”);
    if (unselectedValue == null || (isNaN(selectedItemIndex) && isNaN(hilightedItemIndex)))
    unselectedValue = getStyle(“defaultValue”);

    for(var i:int=0;i<renderers.length;i++)
    renderers[i][stateProperty] = (i == selectedItemIndex)? selectedState:
    (i==hilightedItemIndex)? rolloverState:
    }//endof snippets in

    //in the “main” MXML, this is what is supposed for a developer to do:
    <qs:Fisheye xmlns:qs=”qs.controls.*” height=”100%” dataProvider=”{src}”
    hilightScaleSlope=”3″ hilightMinScale=”.2″
    stateProperty=”currentState” rolloverValue=”rollOver” defaultValue=”” selectedValue=”selected”
    <qs:CachedLabel xmlns:f=”flash.filters.*” color=”#FFFFFF”>
    <State name=”selected”>
    <SetProperty name=”filters”>
    <f:GlowFilter  color=”#888888″/>
    <SetStyle name=”color” value=”#E27C0E” />
    <State name=”rollOver”>
    <SetProperty name=”filters”>
    <f:GlowFilter  color=”#BBBBBB”/>
    //endof main snippets

  2. In some other cases, we don’t know what type (of UIComponent) we would use to render certain data items, or in other words, we like the flexibility of being able to leave the decision up to the developer.

Concept: There is normally a two-tier hook to this kind of things. For case #1, first we store a reference to the _name_ of the property, and provide public ways for the developer to set the name of the property. Under the hood, we query the property name at run-time and wire it back to the parts, which have this property as their data member. After the we know the property of interest, we then retrieve and set all the real values. which actually set values for the aforementioned parts data member. For case #2, we store a reference to the _type_, often as an interface, in our class. When the time comes when we need to declare and initialize one of a concrete type, we take the type that the developer sets, or in the case it’s not defined, we can provide our abstract type.  Till now we can see #2 is usually associated with factory method pattern. It sounds strange and stretchy to me if we call #1 as “Factory property pattern” although it is an innovative attempt.


For #1, they manifest in the form of styles of UIComponent.  The mx.styles.ISimpleStyleClient has a styleName getter which means “the source of this object’s style values”.  One of the scenarios is  the object that implements this interface inherits all the style values from the referenced UIComponen; Another use case is you can use a String which names a class selector that is defined in a CSS style sheet; A third case is to use CSSStyleDeclaration, such as StyleManager.getStyleDeclaration(“.headerStyle”)...

For #2, they appear in IFactory, ClassFactory which are used for creating item renderers.

//sample code for our customcomponent

private var _itemRenderer:IFactory;

public function CustomComponentConstruct()



_itemRenderer = new ClassFactory(Image);


}//end of sample code


//sample code for mx.core.ClassFactory

public var generator:Class

public function ClassFactory(generator:Class = null)

this.generator = generator;
public function newInstance():*
//instantiate new class object. Note that we type "instance" as Object as opposed to Class:
var instance:Object = new generator();
//This is another pattern where we aggregate all children properties to their "owner"
if (properties != null)
for (var p:String in properties)
instance[p] = properties[p];

return instance;
//end of sample code for ClassFactory

Flex pattern: Aggregate sub-component styles into parent

February 7, 2009

Scenario: A lot of times, certain children components share certain properties among them (the values should be all the same for this group of children for this instance of parent component) and yet it would be inappropriate to set them as Static. For example, if you are creating a 3D carousel, the radius of the carousel, the angle between one carousel item to the one next to it, etc. should be the same (ok, the angle could be different for your carousel. So let’s assume it is for mine).

Pattern: Parent creating children . One pattern in Flex, when you create sub-components, you have your parent component does the creation job. In our 3D carousel example, you can have a Carousel component and a CarouselItem component. One of the jobs for Carousel is it becomes a factory of creating contained CarouselItem instances.

Pattern: Aggregating subcomponent styles into parent component. Another pattern in Flex is you can aggregate the styles of your child component into your parent component, even though your parent component does not actually “use” those styles. They are there since it’s convenient and they are automatically passed through to the contained subcomponent.

How: We do this by defining those styles in metadata in the parent component, which assigns itself as the styleName for the subcomponent instances, which makes these instances inherit all the style values defined on the parent component.

//these are the code inside Carousel class

[Style(name=”threeDRadius”), type=”Number”]

override protected function commitProperties():void



for(var i:int=0; i<_dataProvider.length; i++)
var c:CarouselItem = new CarouselItem();

c.styleName = this;


See “Tutorial: DisplayShelf component”

Flex pattern: Lazy validation

January 31, 2009

Lazy pattern is about deferring all the work (processing, rendering, instantiating and/or loading objects) to the time when it is actually needed. This is of a more broader pattern about Asynchronous Processing which implements Two phases commit to process workload.

In the flex Spark component framework, there is this “Validation/Invalidation model” as Deepa Subramaniam calls it which is there to make our code work faster in Flash Player (code execution – rendering per frame in the FP rendering model) .

Scenario: In flex, “Invalidation is a useful mechanism for eliminating duplicate work by delaying processing of changes to a component until a later screen update”. If a user freaks out and drags a coverflow scrubber 100 times a second,  we would like to defer all these crazy requests down to a reasonable volume that we think actually makes sense: For example, if we are running our swf 60 frames/sec, it’s totally reasonable to just process those updates 60 times/sec in maximum right before the rendering phase since all the extra updates would be not only wasted/unseen, but also an overhead for the Player. This is of a kinda humane example. There are probably a lot more times when you need to do this deferring to deal with the internal events from FP or the framework. There are other aforementioned scenarios when you have to coordinate all the different requests (you cannot process one until you have had some other ones being processed), as discussed in Corrollation Identifier Pattern and Competing Consumers Pattern.

Concept: The idea is to cache the requests and separate them from the processing. As in the real world, our immediate response to a request is to take notes, and do the actual work at our leisure later on (mostly as a batch for all work until that moment). Also watch out Starbucks’ decoupling cashier from baristas example next time you go there waiting in a queue. In order to do this in our component framework, additional layers are needed. This is how “dirty flags and storage variables” kicks in.

Solution: Dirty flag and storage variables

We do this by setting up control flags to indicate the state change of the objects of our interest. These flags serve as guards around heavy computations to make sure we’ve only re-calculating what we need to on any given pass. We also need storage variables to remember the requests. When the time to do the real work comes, we check against the guards and do (or bail out and do nothing;) the real processing by referencing to the variables which have stored the request information. The following code demonstrates how mx.core.UIComponent responds to a request to set current state of it:

public function setCurrentState(stateName:String,
playTransition:Boolean = true):void
// Only change if the requested state is different. Since the root
// state can be either null or “”, we need to add additional check
// to make sure we’re not going from null to “” or vice-versa.
if (stateName != currentState &&
!(isBaseState(stateName) && isBaseState(currentState)))
requestedCurrentState = stateName;
playStateTransition = playTransition;

if (initialized)
_currentStateChanged = true;

// We need to wait until we’re fully initialized before commiting
// the current state. Otherwise children may not be created
// (if we’re inside a deferred instantiation container), or
// bindings may not be fired yet.


Why do we need the dirty flags? It’s not always the component that invalidates itself: you should always use flags to mark some potentially intensive processes in the validation phase so they don’t get executed needlessly.

  • When a component changes size, it invalidates its parent’s size and display list.
  • When UIComponent#includeInLayout changes, the parent’s size and display list are invalidated.
  • UIComponent#styleChanged() invalidates the parent’s size and display list.

This pattern as implemented in Spark framework also reminds us of the MVC Pattern. The dirty flags and storage variables actually serve as the controller which handles the requests. The view doesn’t necessarily reflect this request for change in our model until it’s actually been processed. The dirty flags are there to remember whether the Model and View have been synced or not since the last time processing.

There are similar or similarly sounding patterns. One is tied to object initialization (“Lazy Load” with variations such as “Lazy initialization”); and another is about sperating the data being validated from the actual validation implementation (“Data Validation Pattern“), which is somehow different from but yet similar in some aspect to what we are talking about here from a pattern’s point of view (In lazy validation, we seperate what needs to be validated from the processes that actually do the real validation).