Flex in my bank account

May 18th, 2009

This morning I wanted to check out my financial wellbeing or the opposite at least. So I logged into my home-banking account, and selected the overview. This morning things was different, and not related to my actual monetary situation, but due to the nice animating charting component which folded out and showed me a graphical overview.

I was pretty amazed and thrilled for various reasons, first of, the use of the Flash Platform in a banking application is always a great manifest of what is going on; the Flash Platform has made it’s transition from an animation – banner add – micro site – video player -only platform to a state where it is also an enterprise platform. This statement; “Flash Platform is an enterprise platform” is not new at all, I know I for one have preached it to clients over and over the past couple of years, but still, seeing Flash Player used in a home banking app, was a great testimony. As we all know (especially in these times marked in history as “the financial crises”) banks are watching their money with every means there is. So Flash running inside my home banking is a sign of belief and acceptance of the Flash Platform as secure, reliable and suited for enterprise solutions.

Another reason for my happiness as related to a high level view on the RIA sphere I live and work in. I’ve only had a few different banks in my life, so I can’t answer for all of them, but on thing which have been similar to all of them, has been the definition of “overview” when wanting to see your account. The visual presentation of this has always been a refresh of the page followed by a list of dated entries; deposits and withdrawals, and that was it. You could then scroll up and down, and select a new period, and your page would refresh and show a new list, with entries within the new set of calendar boundaries. To see your accounts evolution visually in a graphical chart, first of gives a much nicer overview, you can easily see what’s going on from month to month, or day to day. Being able to easily see the curve of your monetary situation or a comparison between deposits and withdrawals is of great value. When setting the granularity of the graph or the time span in general, no page refresh was needed, the graph just transitioned to its new state, reflecting the data model behind. This was *really* great! A field (at least in Denmark it is) so conservative as the banking sector, implementing a Richness in their Internet Applications is a good step forward and manifest of RIA being a valid use case for better end user experience.

In summery onne might rephrase this to; “One small step for Rich Internet Applications, one giant leap for Home Banking Applications” :-)

Cheers

Asger

Flex, Random Thoughts ,

Flash Builder Browser – the world as it should be

May 16th, 2009

What happend – the motivation
As you might now Flex Builder just got a renaming to the much more coherent Flash Builder.
On of the arguments in favor of the renaming is of cause to lower the misunderstandings between what is Flash, what is Flex, and what is Flex builder.

The Problem
New people in the Flash Platform world is often confused about what is what, when talking about Flex and the Builder tool. This renaming will of cause help solve this in the future. But what about the past? What about all these articles, pages, tutorials etc online which still interchangeably uses Flex and Flex Builder without making a differ?

The Solution
Enter Flash Builder Browser. – your way to see the future, while reading yesterdays news!
Flash Builder Browser is an easy to use browser which alters the content you read, so you wont get confused!
Start getting into the Flash Platform loop with the Flash Builder Browser!

Examples and code
Her is how the world looked yesterday:

And here is how the world looks trough Flash Builder Browser:

Get your own copy of Flash Builder Browser and start seeing the world as it is!
Download AIR application here

Get Involved
Here is the source code, giving you the option to start creating, modifying and improving the Flash Builder Browser.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication width="900" height="900" xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo">
	<s:creationComplete>
		address.text = "http://www.adobe.com/products/flex/"
		browser.location = address.text;
	</s:creationComplete>
	<s:VGroup verticalCenter="0" horizontalCenter="0" height="90%" width="90%">
 
	<s:HGroup width="100%" height="30">
		<s:TextInput width="100%" id="address" />
		<s:Button label="Go" id="goBtn">
			<s:click>
			browser.location = address.text;
			</s:click>
		</s:Button>
	</s:HGroup>
	<mx:HTML width="100%" height="100%" id="browser">
		<mx:htmlRender>
				var flashBuilderPattern:RegExp = /(flex)(®)? +(builder|plugin|plug in)/ig
				if(browser.htmlLoader.window.document.body)
					browser.htmlLoader.window.document.body.innerHTML = String(browser.htmlLoader.window.document.body.innerHTML).replace(flashBuilderPattern,"Flash$2  $3");
		</mx:htmlRender>
	</mx:HTML>
	</s:VGroup>
</s:WindowedApplication>

Happy Coding

UPDATE:
Actually realized that I’d put the regexp code in the htmlRender event, which is not the best place, as it gets called over and over, and could make the browser malfunctioning.
So, even though this post is nothing more than a practical joke, I updated the source, and added some extra things to the usability! (note to self; find a hobby).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication width="900" height="900" xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo">
 
	<fx:Script>
		<![CDATA[
			import mx.managers.CursorManager;
 
			private function goToUrl():void
			{
				browser.location = "http://"+address.text;
			}
		]]>
	</fx:Script>
 
	<s:states>
		<mx:State name="idle" />
		<mx:State name="loading" />
	</s:states>
 
	<s:creationComplete>
		address.text = "www.adobe.com/products/flex/"
		goToUrl();
	</s:creationComplete>
 
	<s:VGroup verticalCenter="0" horizontalCenter="0" height="90%" width="90%">
		<s:SimpleText text="Page Loaded">
			<s:text.loading>Loading page...</s:text.loading>
		</s:SimpleText>
 
	<s:HGroup width="100%" height="30">
		<s:SimpleText text="http://" fontSize="16" fontWeight="bold" />
		<s:TextInput width="100%" id="address" text="{browser.location.replace('http://','')}" enter="goToUrl()" />
		<s:Button label="Go" id="goBtn">
			<s:click>
				goToUrl();
			</s:click>
		</s:Button>
	</s:HGroup>
 
	<mx:HTML width="100%" height="100%" id="browser">
		<mx:complete>
				if(browser.htmlLoader.window.document.body)
				{
					var flashBuilderPattern:RegExp = /(flex)(®)? +(builder|plugin|plug in)/ig
					trace("laver vi søgning???");
					browser.htmlLoader.window.document.body.innerHTML = String(browser.htmlLoader.window.document.body.innerHTML).replace(flashBuilderPattern,"Flash$2  $3");
				}
				currentState = "idle";
		</mx:complete>
 
		<mx:locationChange>
			currentState = "loading";
		</mx:locationChange>
 
	</mx:HTML>
	</s:VGroup>
</s:WindowedApplication>

And of cause the AIR application has been updated as well.

And this I hope is the end of this post *ever* :-D

Download AIR application here

Uncategorized , , ,

ActionScript, RIA and DSL part 1 ½

January 28th, 2009

Introduction
This post is actually a somewhat intermezzo, and wasn’t in my plans. But in my writings of part 1, I happed to post a non working example of a DSL.
I didn’t see the fault my self, but Dmitry Miterev was so kind to point me attention to it. – so I guess this blog post is dedicated to him :)

Background
When I started looking into the opportunities for writing a DSL with AS3, I did a lot of testing and tweaking to see how the language features could help enable me to write a more fluent DSL. Especially the getter / setter features was of great interest as these in their nature removed a lot of noise from the language.

The bad example
In my first post, I pointed out, that to get the Coffee example to work, you could just use a setter returning a reference to the object, containing the property. This can be done, but to things are wrong in the example:

1) It is not possible to type the return type if you want to return the instance:

?View Code ACTIONSCRIPT
package
{
	public class MyClass
	{
		//Not legal setter
		public function set myProperty(value:String):MyClass
		{
			return this;
		}
 
		//Legal setter
		public function set myOtherProperty(value:String):*
		{
			return this;
		}
	}
}

So as you can see, you can mark the setter as ” * ” for an arbitrary value.

2)It is not the feature we are looking fore to solve the design we want in the Coffee example; we need the getter / setter to make the Coffee example work, but the above feature, which for sure can come in handy in DSL cases, is not the one used to create the example.

So what went wrong
I guess writing this post, and playing around with DSL’s in AS 3 for a longer period of time, made me grab, at least what I thought was the, “last working Coffee example” and use that. I guess the lesson is learned; compile and test code before blogging it.

The right example
So without further ado I’ll jump into the Coffee example I actually got to work, when playing around. One thing different though is that the working implementation do not allow for “direct value” like the number defining the temperature of the coffee.
Having reviewed the working example again, I think the best description of the “pattern” if a such can be derived, would be “Reverse Chain Method”, meaning that the last object in the chain, is created first and collects the values from the previous objects in the chain.
But before I turn this blog into a drag like the first part, lets look at the code. – it will also put my definition into context.

The structure
The idea of this way of getting the look and feel of the DSL is to replace the actual class getting instantiated by a subclass (or subclass of subclass) which has the same properties as the base class. So to identify the players in our exampel:
The Coffee class, the class (we think) we manipulate
The Coffee Value, the class representing a value we want to assign to the coffee, say a temperature, a size etc. The CoffeeValue class is a helper class with the logic to perform the revers chaining.
The Concrete value classes, these classes are the concrete implementations of values, so the actual Temperature, Size or Consumption class. These are all sub classes to CoffeeValue, which it self is a subclass to Coffee. To mark the and use the polymorphisms we have a set of marker interfaces, one for CoffeeValue, Template, Size etc.
The complete diagram looks like this:

Reverse Method Chain Diagram

So to start looking at the language we want to build, we have the Coffee example below. As you can see, in this example the temperature now refers to a static property, instead of a value.

?View Code ACTIONSCRIPT
function makeCoffee()
{
	var latte:Coffee = new Coffee()
	.water = ConcreteWater.NO_WATER
	.type = ConcreteCoffeeType.TAZO_CHAI_TEA_LATTE
	.fat = ConcreteFatContent.NON_FAT
	.size = ConcreteCoffeeSize.GRANDE
	.where = ConcreteConsumption.FOR_HERE
	.temperature = ConcreteTemperature.HOT 	
}

Coffe Time
So what happens inside the various classes. I’ll start be looking at the Coffee class, to see how the internals in structured.

?View Code ACTIONSCRIPT
package
{
	public class Coffee
	{
		protected var _size:CoffeeSize;
		protected var _where:Consumption;
		protected var _fat:FatContent;
		protected var _water:Water;
		protected var _temperature:Temperature;
		protected var _type:CoffeeType;
 
		public function Coffee()
		{
 
		}
 
		public function set size(value:*):void
		{
			_size = value;
		}
 
		public function get size():CoffeeSize
		{
			return _size;
		}
 
 
		public function set where(value:*):void
		{
			_where = value;
		}
 
		public function get where():Consumption
		{
			return _where;
		}
 
 
		public function set fat(value:*):void
		{
			_fat = value;
		}
		public function get fat():FatContent
		{
			return _fat;
		}
 
		public function set water(value:*):void
		{
			_water = value;
		}
		public function get water():Water
		{
			return _water;
		}
 
 
		public function set temperature(value:*):void
		{
			_temperature = value;
		}
		public function get temperature():Temperature
		{
			return _temperature;
		}
 
		public function set type(value:*):void
		{
			_type = value;
		}
		public function get type():CoffeeType
		{
			return _type;
		}
	}
}

What is worth noticing in Coffee is that our setters expect an arbitrary data type; this is needed for us to make the chain move backwards, as the same object is being send in to each setter trough out the chain.
Besides the setters the properties is made protected as we need our CoffeeValue helper class to have access to these variables when the chain moves.

Chain, Chain, Chaaiiiin..
Below is the flow of the chain.

Reverse Method Chain Flow

So to recap; The chain starts from the last part of the language, and what happens is, that each line in the Coffee order, which is actually a new CoffeeValue being instantiated, gets collected by the last object in the Chain, finally ending in the “latte” variable.

So lets see what is inside the CofeeValue class:

?View Code ACTIONSCRIPT
package
{
	public class CoffeeValue extends Coffee implements CoffeeSize, CoffeeType, Consumption, FatContent , Water, Temperature, ICoffeeValue
	{
		protected var _value:*;
		private var _property:String;
 
		public function CoffeeValue(property:String,value:*)
		{
			super();
			_property = property;
			_value = value;
			this["_"+_property] = this;
		}
 
		override public function set size(value:*):void
		{
 
			createRef(value);
		}
 
		override public function set type(value:*):void
		{
			createRef(value);
		}
 
		override public function set temperature(value:*):void
		{
 
			createRef(value);
		}
 
		override public function set fat(value:*):void
		{
 
			createRef(value);
		}
 
		override public function set water(value:*):void
		{
			createRef(value);
		}
 
		override public function set where(value:*):void
		{
			createRef(value);
		}
 
		public function get value():*
		{
			return _value;
		}
 
		private function createRef(assignee:*):void
		{
			assignee["_"+_property] = this;
		}
 
	}
}

The trick
So in the CoffeeValue class we do the actual trick. As the class subclasses the Coffee, we override all the setting parts of our setter / getter properties in the Coffee. When we instantiate a CoffeeValue object, we pass two parameters:

1) is the textual name of the property our instance of the CoffeeValue is representing; in an example, if I wanted my object to be the value object for the water, I would pass “water” as the first parameter.

2)The next value is the actual value of the property, in our example I have kept it simple (or as simple as possible :-) ) and just used strings, so in this context it would be “no water” as the value.
Both parameters is saved for later.

What??
So I mentioned the overriding of the setters. What each setter is doing, is calling a private method called “createRef”. What happens in the chain is that the various setters is being called by the various concrete classes. Thus, we need what ever calling class, which has assigned it self as value to the setter, to get it’s property set to the value the called class represents. Puuhhh, that was a tough sentence, but lets put some variables to it. Class’s type = A_TYPE’s size = B_SIZE’s temperature = C_TEMPERATURE. So in this expression, the A,B and C represents the Concrete implementations, which is just different pairs of parameters send to the CoffeeValue. So the chain starts from behind, and C is passed in to B’s set temperature, after that C is passed on to A’s type setter.

So what we make sure in the CoffeeValue setters, -> createRef, is that the class handling the setter, which knows which property it represents (remember it got that from the constructor) assigns it self to the object collecting stuff trough the chain (the last object in the expression or C in our above simplification).

The value parameter is simply saved and used as a easy way to retrieve the value of the CoffeeValue by a get value method.

Concrete Concrete
Don’t worry, it takes a little to get your head around. – and we have yet not seen the actual implementation of a concrete class.
In the DSL I have created the language constructs as “static constants” or that is what they look like at least.
But lets dissect the ConcreteCoffeeSize class (you would of cause go about calling the classes some else than prefixing them with “concrete” but to illustrate what is what I have decided to do so).

?View Code ACTIONSCRIPT
package
{
	public class ConcreteCoffeeSize extends CoffeeValue
	{
		public static function get GRANDE():CoffeeValue
		{
			return new ConcreteCoffeeSize("grande");
		}
 
		public static function get VENTI():CoffeeValue
		{ 
			return new ConcreteCoffeeSize("venti");
		}
 
 
		public function ConcreteCoffeeSize(value:String)
		{
			super("size",value);
		}
 
	}
}

So worth noticing is that this simple class, which merely would normally be a class, has two static getters, each of them returning a new instance of ConcreteCoffeeSize, each with a different setting in value parameter. The constructor of the ConcreteCoffeeSize, is typed to handle the value, given, and providing the property which the class it self represents, to the super() constructor. You could of cause have tons of other logical things inside each concrete class, which differentiated the classes more than just a simple textual value. But for the simple example, and the fact that I’m not building a DSL for employees at StarBucks, I’m an settling for less this time :D

Outro
I guess this wraps this bastard of a blog post up.
Just to touch briefly on the Interfaces used, they are empty except the ICoffeeValue which defines the “get value” function implemented by CoffeeValue.
There is a lot of great possibilities in using a reversed method chain, and definitely room for improvements in my above approach.

Feel free to ask or comment, if there is anything you want to dive into. – maybe you have an even easier way to accomplish the same structure.

Happy Coding

Cheers

ActionScript, Business Domain, DSL, Language Constructs , , ,

Cairngorm Confessions: The Journey

December 28th, 2008

Introduction
Ever felt that there was something wrong with the way you architected your application with the Cairngorm framework?
Well, I for sure have.

Motivation
The motivation for this Flexback Flashback blog-post about my way with Flex and Cairngorm derives from to concurrent events; I’m currently working as a consultant with some great Java and .NET guys. In this project we have decided to use Cairngorm as our architectural framework, a decision I of cause is very happy about. In order to provide the team with an introduction to Cairngorm, I conducted a sample application to support my introduction. This process of going over the various points and parts of the framework led my thoughts back to my own path of learning and using Flex and Cairngorm (which I guess I’m still doing, and hopefully will continue to do). Simultaneously I had to present to a local Adobe RIA User Group meeting, and happened to get the same topic; “Cairngorm”. This concentration of going over Cairngorm and ways to apply it, cerated an overflow of thoughts and memories which is what this post is about. I’ll in the following try to show and tell about how I used Cairngorm, at different steps and level of understanding.

The example domain
In use for my drive down memory lane I have created a business domain called “Cyber Wallet”. The business of Cyber Wallet is an online wallet application in which you can withdraw and deposit money. When ever you do either of the two you create a transaction with a time stamp associated with the money involved. A quick sketch of the Domain Model looks like this:

So this being the simple Domain Model, we can continue on with the Use Cases in the Cyber Wallet application. I have narrowed them down to:

  1. Log In
  2. Log Out
  3. Deposit Money
  4. Withdraw Money

So we’ll take a look at some of these Domain Classes and the Use Cases implemented in various ways. Common for all the examples are that there is 3 main view parts:

  1. a Log In Panel, rendering what is related to authentication use cases (LogInPanel.mxml)
  2. a Wallet Panel, rendering what is related to the wallet use cases (deposit and withdraw) (WalletPanel.mxml)
  3. a Status Panel, rendering what is related to the running transactions related to the wallet use cases (StatusPanel.mxml)

The Money and the Transaction classes will be the same trough out the examples and are implemented as the following:

Money Class

?View Code ACTIONSCRIPT
package model.domain
{
	public class Money
	{
		private var _amount:Number;
 
		private var _currency:String;
 
		public function Money(amount:Number,currency:String)
		{
			_amount = amount;
			_currency = currency;
		}
 
		public function get amount():Number
		{
			return _amount;
		}
		public function get currency():String
		{
			return _currency;
		}
 
		public function toString():String
		{
			return _amount+ " "+_currency;
		}
 
		public function add(money:Money):Money
		{
			//TODO implement logic for adding money
			return new Money(_amount+money.amount,_currency);
		}
		public function substract(money:Money):Money
		{
			//TODO implement logic for subtracting money
			return new Money(_amount-money.amount,_currency);
		}
		public function equals(money:Money):Boolean
		{
			//TODO implement logic to check for different currencies
			return _amount == money.amount;
		}
 
	}
}

Transaction Class

?View Code ACTIONSCRIPT
package model.domain
{
	public class Transaction
	{
		public static const DEPOSITE:String ="deposite";
		public static const WITHDRAW:String ="withdraw";
 
		private var _type:String;
		private var _timeStamp:Date;
		private var _transactionNote:String;
		private var _money:Money;
 
		public function Transaction(type:String,money:Money,notes:String)
		{
			_type = type;
			_money = money;
			_transactionNote = notes;
			_timeStamp = new Date();
		}
 
		public function toString():String
		{
			return "START Transaction: -&gt;"+_type.toUpperCase()+"\n\tDate: "+_timeStamp.toString()+"\n\tAmount:"+_money.toString()+"\n\t" +
					""+_transactionNote+"\nEND Transaction\n--------------------------------------\n";
		}
 
	}
}

Perspective
To put things in perspective I’ll have to mention that I started out with developing larger applications (larger than the “hello world” app) in Flex at the same time that I started looking in to Cairngorm. So my experiences of one or the other could be an effect of the synergy at place when getting your hands to dirty at once.

I have always understood “Model” in the Model-View-Controller pattern to be equivalent to a Domain Model. This Domain-centric Model understanding really troubled my mind when I started looking in to Cairngorm. I felt that the best practices of Cairngorm violated my best practices in terms of having, and working with, real Domain concepts and models. Later I have learned that “Model” in MVC to some is understood as a Service Layer, Transaction Layer or simply a Domain Representation of the Domain Model (but not the actual Domain instance(s)). When looking back on how I at first tried to make Cairngorm work with my actual Domain layer, I clearly see a mixing of clean Domain Models and Domain Representations.

Feeling of something being wrong
First time I got a sign of something being wrong was when I for the first time placed a [Bindable] tag inside a Domain Model object. Coming from the pure AS3 world where my Domain objects always had been nice and clean associated with one another as the would be reflected in the actual business domain, the whole concept of placing a “magic” tag on properties which other objects could bind to, felt wrong. Not the tag, and what the tag in isolation stood for (Broadcasting notification about property changes as any Observer pattern implementation), but what I could see would -, and soon did follow this way of binding view and model together (also; I was starting out in Flex, so messing my domain up, and making them useless for reuse in pure AS3 applications (what they would be, when depending on the [Bindable] tag) also felt bad – now I know I’ll never go back to pure AS3 though.. but I guess I needed the safety net if this “Flex thingie” didn’t turn out to be all that anyway :) ).

What I experienced was that I started composing my models, besides being a reflection of the business domain, also being a reflection of what the view needed. For instance say I was building an application with a use case of a user logging ind, I would consider a User Domain Model object, with data related to the conceptual user. – but building the View (which I understood should bind to the model, hence my User) I would start saying “what do I need in the view to make it run bound to the model? Oh well, I need some state information about whether the user is; logging in, logged in, logging out or logged out”. And I would go about either having a string property on the User object, reflecting these states (which I didn’t like all that much) or build a supporting model like “AuthenticationManager” (early interpretation of my knowledge of a Presentation Model) merely just having the states of the logging in use case. In terms of the problems with the states I kind of felt that I was still within boundary of good practice, excusing my self; “most objects have states, also a user object, right!?!?”. – though I knew that my interpretation of states in an object was much different than just a property holding a string.

Example 1
So given the above, I would properly go about creating my Wallet class like this:

Wallet Class

?View Code ACTIONSCRIPT
package model
{
	import mx.collections.ArrayCollection;
 
	public class Wallet
	{
		public static const STATE_IN_TRANSACTION:String = "stateInTransaction";
		public static const STATE_IDLE:String ="stateIdle";
 
 
		[Bindable]
		public var balance:Money;
 
		private var transactionLog:ArrayCollection;
 
		[Bindable]
		public var transactionNotes:String = "";
 
		[Bindable]
		public var state:String = STATE_IDLE;
 
		public function Wallet()
		{
			balance = new Money(0,"dollars");
			transactionLog = new ArrayCollection();
		}
 
		public function deposite(money:Money,notes:String):void
		{
			balance = balance.add(money);
			var trans:Transaction = new Transaction(Transaction.DEPOSITE,money,notes);
			transactionLog.addItem(trans);
			transactionNotes+=trans.toString();
		}
 
		public function withdraw(money:Money,notes:String):void
		{
			balance = balance.substract(money);
			var trans:Transaction = new Transaction(Transaction.WITHDRAW,money,notes);
			transactionLog.addItem(trans);
			transactionNotes+=trans.toString();
		}
	}
}

Notice the [Bindable] tags on the balance and the transactionNotes properties. Beside these Domain related properties a state property and corresponding state constants has been declared as well. These would be used for the view to change to the appropriate View state, when the wallet changed.
So a lot of View specific properties not really related to the Domain implementation of the Wallet.

When creating the WalletPanel in the application which would have the responsibility of render the amount of the Wallet to the screen, and providing controls for depositing and withdrawing money, we can now directly bind to the balance property of the Wallet.

WalletPanel View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%">
<mx:Script>
    <![CDATA[
        import event.WithdrawEvent;
        import event.DepositeEvent;
        import model.ModelLocator;
 
        //No dependency injection, but directly accessing the ModelLocator
        [Bindable]
        private var _model:ModelLocator = ModelLocator.getInstance();
    ]]>
</mx:Script>
    <mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
 
    <!-- Directly look up, in the model locator, 
        ... to access the wallet's balance's amount and currency
         ... NOT a good approach for dynamic and reusable views -->
 
        <mx:Label text="Wallet Balance is {_model.wallet.balance.amount +' '+ _model.wallet.balance.currency}" fontSize="30" />
        <mx:HBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
            <mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                <mx:TextInput restrict="0-9" id="depositeInput" />
                <mx:Button label="Deposite">
                    <mx:click>
                        <![CDATA[
 
                            // Directly dispatching of Cairngorm (Use Case) events from within the view
                            var de:DepositeEvent = new DepositeEvent();
                            de.data = Number(depositeInput.text);
                            de.dispatch();
                        ]]>
                    </mx:click>
                </mx:Button>
            </mx:VBox>
            <mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                <mx:TextInput restrict="0-9" id="withdrawInput" />
                <mx:Button label="Withdraw">
                    <mx:click>
                        <![CDATA[
 
                            // Directly dispatching of Cairngorm (Use Case) events from within the view
                            var we:WithdrawEvent = new WithdrawEvent();
                            we.data = Number(withdrawInput.text);
                            we.dispatch();
                        ]]>
                    </mx:click>
                </mx:Button>
            </mx:VBox>
        </mx:HBox>
    </mx:VBox>
</mx:Panel>

Okay, to touch on some practices, I have in the above MXML component (and in the rest of the examples) really made an effort in showing some critical points where you should watch how you implement your rendering in the view.
First is the lack of dependency injection; I directly reference the ModelLocator to retrieve the instance of wallet. This is not a favorable approach, as this couples our view unnecessary to the Cairngorm framework (The ModelLocator pattern) – also by not having the dependent Wallet injected at runtime, we miss the opportunity of resetting the component later, by injecting a new Wallet.

Furthermore the DepositeEvent and WithdrawEvent, which is CairngormEvents representing application Use Case Events, are created and dispatched directly from WalletPanel. This approach presents some problems; again the coupling between the view and Cairngorm is unnecessary and our view would not be reusable in another application without modification. Another more underlying thing is that there is no other mediator between views than the actual Domain Model objects. So every change in our view, which might be of interest to other views, would have to be reflected in the Domain Model and the update in the view would have to be related to a Use Case/ CairngormEvent and trigger a around trip in the application(Event -> Controller -> Command -> Model -> View).
To give an overview of what I mean, you should take a look at the below diagram:

A UML diagram of the structure of the application
ex1diagram

Here is the CyberWallet application implemented with the above state of mind. You can view the source by right clicking and choosing “View Source”.  Bear in mind that the application is not created to show case Flex specific things, and *yes* I know a lot could have been done smarter, better, easier,… etc. – these things is not the focus of this post. But what you *should* notice is the way Cairngorm is setup, and how the view retrieves the Model, how it communicates with the controller layer and how the Model is implemented to provide view-centric/specific needs.
I wont go over the other use cases and view parts, as you can see them for your self, in the source. I have commented here and there to point out the violations mentioned above.

The next big step
After working around for some time, getting more and more familiar with Flex and of cause Cairngorm, I started getting rid of some of the “teething troubles”. All the apparent issues from the example above; better dependency injection, decoupling between view and Cairngorm and a better formalization and evolution of the supporting model objects (-managing, -monitoring …). I started looking at these classes or coherent collections of responsibility as representational model objects; representational in the way, that these objects would represent smaller or larger parts of the Domain, without being an actual Domain Model them selves. If I today should categorize them I would say that they where “Passive Presentational Models” or “Ultra Thin Presentational Models”. – if you are not familiar with Martin Fowlers work on “Organizing presentation logic“, you should definitely take at look.

This way of moving away from having view-needed properties in the Domain, and instead having coherent parts of the Domain represented in “Thin Presentation Models” felt better. “A snake in paradise”- as my architecture started looking better when facing the model layer, I had started getting a lot of concerns in terms of how much logic to have in the Views. I had tried code behind for a while, which I really didn’t like due to the strong coupling, I turned to a more “View Helper” centric approach, where a view would have a helping class, handling events, states etc. – they never really felt like the best solution, and even though it wasn’t coupled trough inheritance like Code Behind, but trough composition, I had the same “to tight coupled” feeling as I had with Code Behind.

Another thing I didn’t like was the “one view, one helper” situation. -I really wanted to find a pattern where multiple views could feed from the same “source”. So I actually returned to putting logic back to the view. I started using an “Aggregated  View” pattern (there is no such pattern, but I invented the term internaly when talking about this aproach), where I would declare the new  Cairngorm-decoupled, reusable view components. These view components would depend on a “Thin Presentation Model” and be structured inside a custom wrapping view managing multiple components; hence the name “Aggregated View”. The idea was to have as much reusable code in coherent components, and let the “Aggregated View” handle the dependency injection, and gathering component level events, and interpreted them into use case events / CairngormEvents if necessary. This way the custom code would be minimized to evolve around setting up the reusable components, and only be inside these AggregatedView phenomenoms.

Example 2
From example 1, to 2, there is two very distinct points I would like to iterate over. First I will take a look at how the Domain Model is held clean, and the use of the “Thin Presentation Model” – called Representation i the following, as it is not an actual implementation of the Presentation Model pattern.
Next I’ll look at the “Aggregated View” I mentioned before, to show how our custom have been limited to a central mxml file (view).

The Wallet revisited
Lets start by looking at the revisited Wallet class in the Domain layer. What you should notice is the total removal of [Bindable] tags. As mentioned earlier, I’m not a big fan of these in Domain Models. Instead you’ll see that the Wallet now is an EventDispatcher descendant, and that I have introduced a TransactionEvent, being fired when ever a Transaction has occurred in the Wallet. The state property is gone as is the transactionNotes. These responsibilities would now be found in the Representation of the Wallet. This way of having the Domain Cleaned out, only using pure ActionScript features such as dispatching events etc, is how I still is implementing my Domain Models today.

Wallet Class

?View Code ACTIONSCRIPT
package model.domain
{
	import event.TransactionEvent;
 
	import flash.events.EventDispatcher;
 
	import mx.collections.ArrayCollection;
 
	public class Wallet extends EventDispatcher
	{
		public var balance:Money;
 
		public var transactionLog:ArrayCollection;
 
		public function Wallet()
		{
			balance = new Money(0,"dollars");
			transactionLog = new ArrayCollection();
		}
 
		public function deposit(money:Money,notes:String):void
		{
			balance = balance.add(money);
			var trans:Transaction = new Transaction(Transaction.DEPOSITE,money,notes);
			transactionLog.addItem(trans);
			dispatchTransaction(trans);
		}
 
		public function withdraw(money:Money,notes:String):void
		{
			balance = balance.substract(money);
			var trans:Transaction = new Transaction(Transaction.WITHDRAW,money,notes);
			transactionLog.addItem(trans);
			dispatchTransaction(trans);
		}
 
		private function dispatchTransaction(t:Transaction):void
		{
			var te:TransactionEvent = new TransactionEvent("transaction");
			te.transaction = t;
			dispatchEvent(te);
		}
	}
}

The EconomyRepresentation
So getting rid of the view and Flex specific noise in the Domain, we can now take a look at the new Representation class used to provide the view specific information from the Wallet. Instead of naming my Representation something like WalletRepresentation, which would remind me to much of the one – to -one mapping in the View Helper pattern, I would name it EconomyRepresentation. As stated, my hope was to move towards a set of patterns giving my a central coherent place for multiple views to subscribe to Domain data. – thus, by going for a broader Representation term, and also the responsibility, I would get a class which could serve all views with interest in presenting parts of the aggregated Domain related to economy.

EconomyRepresentation Class

?View Code ACTIONSCRIPT
 
package model.presentation
{
	import event.TransactionEvent;
 
	import model.domain.Wallet;
 
	public class EconomyRepresentation
	{
		[Bindable]
		public var transactionLog:String ="";
 
		[Bindable]
		public var balance:String;
 
		private var _wallet:Wallet;
 
		public function EconomyRepresentation(wallet:Wallet)
		{
			_wallet = wallet;
			init();
		}
 
		private function init():void
		{
			balance = _wallet.balance.toString();
			_wallet.addEventListener("transaction",walletTransactionHandler);
		}
 
		private function walletTransactionHandler(te:TransactionEvent):void
		{
			transactionLog+= te.transaction.toString();
			balance = _wallet.balance.toString();
		}
 
	}
}

As you can see, the EconomyRepresentation has a reference to the Wallet Domain object. It subscribes to the transaction event broadcasted by Wallet. When this broadcast is handled the EconomyRepresentation updates it’s balance, which compared to the balance of Wallet, is just a string, and the transactionLog compared to the transactionLog in Wallet which is of type ArrayCollection, is again just a string representing the log of the Wallet.
As I think this way of cleaning and separating (re)Presentational logic from the Domain is very essential, I’ll show you the AuthenticationRepresentation and the ApplicationRepresentation as well. These two classes is of cause used to represent the authentication related data and state of the application and the state of the actual-application (actual-application; the overall state of the application). The latter being the workflowState declared directly on the ModelLocator in Example 1 (run the example and view the source).

AuthenticationRepresentation Class

?View Code ACTIONSCRIPT
package model.presentation
{
	import flash.events.EventDispatcher;
 
	public class AuthenticationRepresentation extends EventDispatcher
	{
		public static const LOGGING_IN:String ="loggingIn";
		public static const LOGGED_IN:String ="loggedIn";
		public static const LOGGING_OUT:String ="loggingOut";
		public static const LOGGED_OUT:String ="loggedOut";
		public static const LOGGING_IN_FAULT:String ="loggingInFault";
 
		[Bindable]
		public var state:String = LOGGED_OUT;
 
		[Bindable]
		public var userName:String;
 
		public function AuthenticationRepresentation()
		{
 
		}
 
	}
}

The above is simply just the states we had in the AuthenticationManager plus the userName property.

But what is interesting is to be seen in the following example of the ApplicationRepresentation class

ApplicationRepresentation Class

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package model.presentation
{
	import model.ModelLocator;
 
	import mx.events.PropertyChangeEvent;
 
	public class ApplicationRepresentation
	{
		public static const AUTHENTICATION:String = "authentication";
		public static const IDLE:String = "idle";
 
		[Bindable]
		public var state:String = AUTHENTICATION;
 
		private var _authModel:AuthenticationRepresentation;
 
		public function ApplicationRepresentation(authModel:AuthenticationRepresentation)
		{
			_authModel = authModel;
			init();
		}
 
		private function init():void
		{
			_authModel.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE,authModelChanged);
		}
 
		private function authModelChanged(e:PropertyChangeEvent):void
		{
			if(e.newValue == "loggedIn")
				state = IDLE;
			else if(e.newValue =="loggedOut")
				state = AUTHENTICATION;
		}
 
	}
}

- the ApplicationRepresentation is dependent on another Representation, to manage it’s states. This is for me a vital feature in the design; being able to structure hierarchical Representations of the Domain. If you look at the source of Example 1 you would see that in the LogInCommand I would manipulate both the state of the AuthenticationManager *and* the workflowState property of the ModelLocator. To me, it is more sound to have an association-structure among these Representation models, as we have it at the Domain level of the model. Instead of having our controller feature of the architecture coupled to how our representation is laid out, the LogInCommand should only worry (and know) Representation and/or Domain objects related to pure concept of “Loggin In” – and not derivations!

The Aggregated View
As we looked at the WalletPanel in example 1, I’ll take my point in the same view part here. – the rest of the view implementations can been seen by running the example linked to below, and selecting to view the source.

WalletPanel View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%">
<mx:Metadata>
    [Event(name="withdraw")]
    [Event(name="deposite")]
</mx:Metadata>
<mx:Script>
    <![CDATA[
 
        //Balance is dependent on injection, instead of self-retrieved the data.
        [Bindable]
        public var balance:String
 
        public var depositAmount:Number;
 
        public var withdrawAmount:Number;
    ]]>
</mx:Script>
    <mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
        <mx:Label text="Wallet Balance is {balance}" fontSize="30" />
        <mx:HBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
            <mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                <mx:TextInput restrict="0-9" id="depositeInput" />
                <mx:Button label="Deposit">
                    <mx:click>
                        <![CDATA[
                            depositAmount = Number(depositeInput.text);
                            dispatchEvent(new Event("deposite"))
                        ]]>
                    </mx:click>
                </mx:Button>
            </mx:VBox>
            <mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                <mx:TextInput restrict="0-9" id="withdrawInput" />
                <mx:Button label="Withdraw">
                    <mx:click>
                        <![CDATA[
                            withdrawAmount = Number(withdrawInput.text);
                            dispatchEvent(new Event("withdraw"))
                        ]]>
                    </mx:click>
                </mx:Button>
            </mx:VBox>
        </mx:HBox>
    </mx:VBox>
</mx:Panel>

If we look at the above, we see that the WalletPanel firstly defines some component-context events in the metatags, and that there is no dispatching of CairngormEvents from inhere anymore. This separation keeps the WalletPanel decoupled from the CairngormEvents, and instead we are able to handle the two component-defined events as we want out side of the component (for instance mapping them to CairngomEvents/use cases). Next, the balance property is declared as bindable thus making it an injection hole from the outside world, into the WalletPanel. The WalletPanel do not have to rely on the ModelLocator or any Domain Models to get its data; it simply expects it to be injected. In a matter of convenience I have provided the WalletPanel with two public properties, used by the outside world to retrieve the deposit and withdraw amounts respectively.
To make this new revision of the WalletPanel, and the other new view components work, we need to look at our “AggregatedView”. In Example 1, we already had a view class aggregating and laying out the components; the LayoutView.

The LayoutView has in this example been modified to hold the application-specific code gluing the cleaner panel components and the representations together. The LayoutView works as a Mediator for the containing components, and injects their dependencies when declaring them. Lastly it handles the component-specific and dispatches the equivalent Use Case events (CairngormEvents).

LayoutView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" 
    height="100%" xmlns:login="view.login.*" xmlns:status="view.status.*" 
    xmlns:wallet="view.wallet.*"
    currentState="{_model.applicationModel.state}">
<mx:Script>
    <![CDATA[
        import event.WithdrawEvent;
        import event.DepositEvent;
        import event.LogOutEvent;
        import vo.UserVO;
        import event.LogInEvent;
        import model.ModelLocator;
        [Bindable]
        private var _model:ModelLocator = ModelLocator.getInstance();
 
        private function handleLogIn(event:Event):void
        {
            var user:UserVO = new UserVO();
            user.userName = loginPanel.user;
            user.password = loginPanel.pass;
            var loginEvent:LogInEvent = new LogInEvent();
            loginEvent.data = user;
            loginEvent.dispatch();
        }
        private function handleLogOut(event:Event):void
        {
            new LogOutEvent().dispatch();
        }
        private function handleDeposit(event:Event):void
        {
            var de:DepositEvent = new DepositEvent();
            de.data = walletPanel.depositAmount;
            de.dispatch();
        }
        private function handleWithdraw(event:Event):void
        {
            var we:WithdrawEvent = new WithdrawEvent();
            we.data = walletPanel.withdrawAmount;
            we.dispatch();
        }
    ]]>
</mx:Script>
    <mx:VBox id="leftPanel" horizontalAlign="center" horizontalCenter="0">
        <status:StatusPanel id="statusPanel" statusLog="{_model.ecoModel.transactionLog}" />
        <login:LogInPanel id="loginPanel" authenticationModel="{_model.authenticationModel}" 
            logIn="handleLogIn(event)"
            logOut="handleLogOut(event)" />
    </mx:VBox>
    <wallet:WalletPanel id="walletPanel" balance="{_model.ecoModel.balance}" 
        deposite="handleDeposit(event)" withdraw="handleWithdraw(event)">
    </wallet:WalletPanel>
 
    <mx:states>
        <mx:State name="authentication">
            <mx:SetProperty target="{statusPanel}" name="width" value="0" />
            <mx:SetProperty target="{statusPanel}" name="height" value="0" />
            <mx:SetProperty target="{walletPanel}" name="width" value="0" />
            <mx:SetProperty target="{walletPanel}" name="height" value="0" />
            <mx:SetProperty target="{leftPanel}" name="width" value="100%" />
            <mx:SetProperty target="{leftPanel}" name="height" value="100%" />
            <mx:SetProperty target="{loginPanel}" name="width" value="25%" />
            <mx:SetProperty target="{loginPanel}" name="height" value="25%" />
        </mx:State>
        <mx:State name="idle">
            <mx:SetProperty target="{statusPanel}" name="width" value="100%" />
            <mx:SetProperty target="{statusPanel}" name="height" value="100%" />
            <mx:SetProperty target="{walletPanel}" name="width" value="100%" />
            <mx:SetProperty target="{walletPanel}" name="height" value="100%" />
            <mx:SetProperty target="{leftPanel}" name="width" value="25%" />
            <mx:SetProperty target="{leftPanel}" name="height" value="100%" />
        </mx:State>
    </mx:states>
 
    <mx:transitions>
        <mx:Transition fromState="*" toState="*">
            <mx:Resize targets="{[walletPanel,leftPanel,statusPanel,loginPanel]}" />
        </mx:Transition>
 
    </mx:transitions>
</mx:HBox>

Here is an overview of the application in UML. I have in the diagram also showed the Business package, which is not implemented in the example. This is only to show how it would have been implemented until now. A Command would instantiate a Delegate, which would use a service found in the ServiceLocator. The Delegate would be the first to handle the result back from the Service, massaging it in any way needed for the application. This could for instance be an XML stream needed to be parsed to the equivalent object hierarchy. After this, if any, data massaging the data would be send back to the Command, as a response. This way the only place where a Service and raw data manipulation would be at place, would be in the Delegate classes.

You can see the example and view the source here.
Key points in this example was the cleaning of the Domain layer and the more powerful Representation models. The view also got cleaner and an “AggregatedView” gluing it all together, providing injection and providing mediation between Views was created.

The real Presentation Model
At this time in my Cairngorm journey I started feeling good again about my work as an Architect , or as Ben Stucki might have put it; I started to move my Developer <-> Architect slider thumb, more towards the Architect end again (see Bens’s great talk about Developers and Architects). The way the cleaning of the Domain layer had turned out, was satisfying and reusable components decoupled from their surroundings also felt good. My own interpretation of a Presentation Model aka Representations also did the job good, and abstracted the Domain towards the view. But I still felt I had two challenges: My AggregatedViews also got the job done but their internals was not a pretty sight; custom code gluing it all together, seamed to call for a bloated script tag inside the MXML file. – further I still wasn’t to happy about the View. As mentioned I went back towards the Autonomous View pattern. -where a view manages it’s own presentation logic and state (or greater parts of it, as in example 2).

So the next step on my journey was to take a deeper look at the *real* Presentation Model, which fitted good into my current setup:

  1. My currently implemented Representation layer could easyli evolve into a real Presentation Model
  2. My AggregatedView could be cleaned and the Presentation Model could encapsulate the component/use case specific code, and mediate for multiple views
  3. My semi- Autonomous View could have it’s logic extracted and be a “dumb view” not knowing to much.

So by evolving my Representation into a Presentation I could get closer to a solution to the two above mentioned challenges.

Example 3
To illustarate how to move the logic from  the View into a Presentation Model, I’ll return show how the Authentication Representation class ended up, as Authentication Model:

AuthenticationModel Class

?View Code ACTIONSCRIPT
package model.presentation
{
	import event.LogInEvent;
	import event.LogOutEvent;
 
	import flash.events.EventDispatcher;
 
	import vo.UserVO;
 
	public class AuthenticationModel extends EventDispatcher
	{
		public static const LOGGING_IN:String ="loggingIn";
		public static const LOGGED_IN:String ="loggedIn";
		public static const LOGGING_OUT:String ="loggingOut";
		public static const LOGGED_OUT:String ="loggedOut";
		public static const LOGGING_IN_FAULT:String ="loggingInFault";
 
		[Bindable]
		public var canLogIn:Boolean = false;
 
		[Bindable]
		public var status:String = "";
 
		private var _userName:String;
		private var _userNameIsValid:Boolean = false;
		private var _password:String;
		private var _passwordIsValid:Boolean = false;
 
		private var _currentState:String ="";
 
		public function AuthenticationModel()
		{
			state = LOGGED_OUT;
		}
 
		/**
		 * API method to logIn
		 *
		 */
		public function logIn():void
		{
			if(canLogIn)
			{
				var user:UserVO = new UserVO();
				user.password = _password;
				user.userName = _userName;
 
				var le:LogInEvent = new LogInEvent();
				le.data = user;
				le.dispatch();
			}
		}
 
		public function logOut():void
		{
			//TODO implement logic to secure that log out can take place
			userName = "";
			password = "";
			new LogOutEvent().dispatch();
		}
 
		[Bindable]
		public function set state(value:String):void
		{
			//TODO implement logic for setting state
			_currentState = value;
			if(value == LOGGING_IN)
				status = "Logging In";
			else if(value == LOGGED_IN)
				status = "Logged In";
			else if(value == LOGGING_OUT)
				status = "Logging Out";
			else if(value == LOGGED_OUT)
				status = "Logged Out";
 
		}
		public function get state():String
		{
			return _currentState;
		}
 
		public function get userName():String
		{
			return _userName;
		}
 
		[Bindable]
		public function set userName(value:String):void
		{
			_userName = value;
			validateUserName();
		}
 
		public function get password():String
		{
			return _password;
		}
 
		[Bindable]
		public function set password(value:String):void
		{
			_password = value;
			validatePassword();
		}
 
		/**
		 * INTERNAL validation methods
		 *
		 */
		private function validateUserName():void
		{
			//TODO implement validation logic and rules
			_userNameIsValid = _userName.length &gt; 3;
			validateLogIn();
		}
		private function validatePassword():void
		{
			//TODO implement validation login and rules
			_passwordIsValid = _password.length &gt; 3;
			validateLogIn();
		}
		private function validateLogIn():void
		{
			canLogIn = _passwordIsValid &amp;&amp; _userNameIsValid;
		}
	}
}

Looking at the above we can see that our Authentication Model actually has an API (logIn and logOut) that reflects the use cases we want our Presentation Model to present. These two methods are now handled accordingly to the state of the Model. If, in this case, the password and user name checks out, a CairngormEvent is dispatched to be taken care of by the controller -> command structure. Besides this API you should see that the validation, and enabling of the ability to login is handled by the Model. This is handles by letting the View set the user name and password data each time it changes in the view. – thus making the actual view very thin in terms of knowledge.

I’m still presenting the state of the model as a string (though arguable the state is now composed by multiple data variables) but in other and more complex Presentation Models could easily have a real state (machine) pattern implementation.

Now that we have glimpsed at the new Presentation Model implementation, lets see how the actual View has been changed to correspond to this. In this example I have chosen the LogInPanel as it uses the AuthenticationModel just described. You should check out the running example 3 to see the full source.

LogInPanel View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAlign="center" verticalAlign="middle" 
    layout="vertical" width="100%" height="100%"
    currentState="{authPM.state}" title="{authPM.status}">
<mx:Script>
    <![CDATA[
        import model.presentation.AuthenticationModel;
 
        [Bindable]
        public var authPM:AuthenticationModel;
 
    ]]>
</mx:Script>
    <mx:states>
        <mx:State name="loggedOut">
            <mx:AddChild>
                <mx:VBox>
                 <mx:Form>
                    <mx:FormItem label="User Name:">   
                        <mx:TextInput id="userName" change="authPM.userName = userName.text" text="{authPM.userName}" />
                    </mx:FormItem>
                    <mx:FormItem label="Password">
                        <mx:TextInput id="password" displayAsPassword="true" change="authPM.password = password.text" text="{authPM.password}" />
                    </mx:FormItem>
                </mx:Form>
                </mx:VBox>
            </mx:AddChild>
            <mx:AddChild>
                <mx:ControlBar>
                    <mx:Button label="Log In" enabled="{authPM.canLogIn}" click="authPM.logIn()" />
                </mx:ControlBar>
            </mx:AddChild>
        </mx:State>
        <mx:State name="loggingIn">
            <mx:AddChild>
                <mx:Label text="Logging in, please wait..." fontSize="22" />
            </mx:AddChild>
        </mx:State>
        <mx:State name="loggedIn">
            <mx:AddChild>
                <mx:VBox>
                    <mx:Label text="You are logged in as {authPM.userName}" />
                </mx:VBox>
            </mx:AddChild>
            <mx:AddChild>
                <mx:ControlBar>
                    <mx:Button label="Log Out" click="authPM.logOut()" />
                </mx:ControlBar>
            </mx:AddChild>
        </mx:State>
        <mx:State name="loggingOut">
            <mx:AddChild>
                <mx:Label text="Logging out, please wait..." fontSize="22" />
            </mx:AddChild>
        </mx:State>
    </mx:states>
</mx:Panel>

As you can see; the View is much cleaner and stripped from most of the logic. After the reference to the AuthenticationModel gets injected the LogInPanel binds all its View Controls to state and properties of the Model. The change event fired from the TextInput fields is defined to set the property on the Model, and the buttons’ click events are triggering parts of the Models interface.

With the thinning of the View our AggregatedView also get stripped down, actually to only having the responsibility to inject the dependencies (and in our case to lay out the components).

You should take a look at the source in example 3.

Another thing worth noticing is that in my example, I have two kinds of Presentation Models; one being strictly the Abstracted View logic, and nothing more (Authentication Model) and the other being both an Abstracted View Model but also a Domain related Representation (Economy Model as it is directly associated and defined by states in Domain Model objects). I call them the Self Sustained Presentation Model, and the Domain Sustained Presentation Model respectively. We could even go further and claim that the Application Model in the Examples is a Specialized Presentation Model as it’s presentation ground remains on other Presentation Models, hence the specialization.

Overview
So lets look at how the structure is.
In the below UML diagram I have sketched out how the concepts and patterns collaborate in example 3. I have not named the classes as they are named in the Cyber Wallet domain, but as their role in the architecture. As in the diagram in example 2, I have included the Business package of the architecture, thugh it is not implemented and discussed in the examples. In this state of the architecture a new “player” has entered the field; the responder. In stead of having the delegate class or the command handling the respons from the business layer, an actual responder is given the responsability of handling and massaging data. So in terms of the GRASP (-patterns) the coherent responsability of handling business respons, is moved from either the command which only executes in regard to its concrete implementation and the delegate only delegates the business tier, to a responder (in the diagram the Responder and the Delegate should also be understood as conceret implementations of the concepts respectively).

Retrospective
The Presentation Model provided a good solution to my two mentioned challenges. The View got thinner, the AggragatedView got cleaned out, and the Representation Models matured and grew up and took on more coherent responsibility. And this is about where I am to day. I’m constantly looking at new patterns, thinking about ways to improve here and there. There is still many places where I haven’t been with Cairngorm yet, so I’m sure that my journey is far from over. – I hope it’s not. I hope there is many miles left to be wandered, as sometimes it’s not what you ended up with that matters the most, but the way you got it! It has been great walking down memory lane, and fun to see how perspective and understanding changes over time.

Looking a head I’m very excited to see Gumbo/Flex 4 evolve. As I write this, a lot of the specs for the new Flex 4 component architecture has been released. This new separation between presentation logic and graphical View is very interesting and I am really looking forward to how this will be adding to the next step in my Cairngom journey, and the way I work together with the great designers in our team.

My first Cairngorm Confession is over; a journey looking back at the last couple of years in my life with Cairngorm and Flex. It has been great to stroll down memory lane. I hope you enjoyed it as well.
Again, I want to re-iterate that the examples isn’t created to show best practices in Flex, maybe not even in Cairngorm, but to support my rambling about the concepts I got to know and evolve around in my journey. I might find the time to clean the examples up, and make them nice and consistent, but for now I hope you’ll live without and are able to derive the essence of my points.

ActionScript, Cairngorm, Cairngorm Confessions , , , , , ,

ActionScript, RIA and DSL’s part 1

December 14th, 2008

Introduction
For some time now, I have been wanting to take a closer look at Domain Specific Languages (DSL) and their whereabout in Rich Internet Applications. Actually I got interested in the subject at the JAOO conference earlier this year.
Here I got the chance to participate in a full days tutorial in DSL’s held by Martin Fowler and Neal Ford from Thought Works. The tutorial took a deep dive into the general definition of a DSL and looked at the various ways to build and provide DSL’s domain experts. Later at the JAOO I had the great pleasure of being at James Wards session on RIA with Flex and AIR. In this session

James demoed a use case related to the insurance domain. The use case evolved around how to file a car crash with your insurance company. The application showed how an applicant would go about describing the car crash by placing his own car and other implicated cars in an intersection, in a graphical environment.
This depicting of a business case combined with my newly awakening in the world of DSL’s got me thinking about the way many of us use RIA as a way to communicate a limited business domain trough a rich interface.
As I realize this subject might take some time for me to get my head around, therefor I have decided to make it a series. In this first part I’ll try to get around what (I think) a DSL is, and how you could build a internal DSL in ActionScript.

What’s an DSL
The general definition is that an DSL is a language which is specific to a certain problem domain. As opposed to General Purpose Language, a DSL or “special purpose language” as some might call them, is constraint to provide meaning to the business domain and nothing more. It is by default defined to be a Computer Programming Language with limited expressiveness. The wikipedia also includes “visual diagramming language” as part of the definition. So in broad terms a way to communicate a domain to/with a computer.

To put this into a little perspective (though I just stated that an DSL IS in some way related to a Computer) I like to think of a DSL, or at least the way a language is limited to a domain, as the way to order a coffee at Starbucks.
If you are not familiar with the Starbucks jargon, you should check out this wiki explaining how to order by using the Starbucks “DLS”. For instance the order: I’ll have a ‘For Here’, Grande, Non-Fat, No Water, 180 Degrees, Tazo® Chai Tea Latte is an example of an order at Starbucks. Further; this sentence only makes sense to the Starbucks business domain, it has a limited expressiveness and the syntax is human readable, though simplified.

This is of cause a simplification of the DSL explanation (and again, the Starbucks jargon, is just a jargon or “slang” vocabulary), but it gives a relational mapping from our world to the way we need to think of DSL in terms of a domain specific computer language.
Besides the above points and some more specific rules of thumb (like a DSL never should have touring completeness etc.) it is hard to set exact boundaries for a DSL; domains are different and the need for expressiveness or the ability to limit scope varies.

Why even bother
Before we walk further down the DSL road I think it is in good order to motivate why one would even go about spending time and effort on this subject. I see a close connection between Rich Internet Applications and the way we can use DSL as part of solving a problem. We deal with domain users and domain experts on a daily basis, as we both have to capture what the business domain is all about, and create the interface that make the user collaborate with this domain. A lot of the applications we build, is created with an expressive and rich interface. – Interfaces which, in my point of view, can be exactly that visual abstraction on top of a problem domain, the wikipedia calls: “visual diagramming language”. I’ll in the following try to showcase what I think a DSL is, and how it is implemented internally and externally (in code and/or graphically).

In the attempt to get my own (and hopefully your) head around how some thoughts about DLS’s could benefit the way we think about creating (Rich Internet) Applications, we need a little “case” project”  This “case” will be the context to which I can refer troughout this post (and in later parts). I’ll try to outline a VERY simplified business domain (so please don’t ask to many clarifying quesitons about this given scenario, I promise I’ll return in a later part with a more “real world” piece of meet).

Our point of entrance case
So lets say we are building an application which is to be used by a big chain of bakeries to control the pipeline of bread being baked every day. The bakers will be using the application to look up recipes, provided trough a graphical step by step user interface, making it easy for even novice bakers to follow along and bake bread.

Our domain clearly evolves around the bakery-domain, where we need to focus especially on the Recipe Model as that is what our application will do a lot of work with. When we start our work with the domain expert; the experienced chief baker. From him we learn that the bakery chain already have a lot of recipes laying around.
All these should be “programmed/stored” in to our system (for instance into a database) at start up, so that the application from day one will be able to show all the recipes used today. Besides that; every day, new and exotic recipes are discovered world wide, and the chief baker, wants an easy way to provide new recipes to the baker system. These new recipes could be found in a news paper or book, send to the chief on a mail,  or sometimes the chief baker even receives recipes on a bar napkins (from a fellow bakers stroked by  moments of bread-creativity when drinking heavily).

So what options do we have for providing a means for the chief baker to get all the recipes into the system. One option would be to create a form, maybe even just one big text field for the chief to write a recipe into, exactly as it would read in the book, paper or mail. But this solution isn’t good (for various reasons) as we need to remember; the application is suppose to guide the bakers trough the recipe thus having to break the recipe up in to coherent chunks. This will be impossible to say the least, to do with one big string of text. So another option would be to create multiple text fields each representing a step in the recipe, for the chief to fill in. This way the chief as the domain expert would have the ability to chunk the recipe up into coherent steps which would make sense when baking the bread.

Though this solution seams better at first, I think there is a lot to be cautious about in an approach like this. First of all; chunking the recipe up and gathering it up by a series of fields do not give us much more about the recipe besides the chunks them selves. If we want to use the data in the recipes to anything besides just showing the text representing a step, we would have a hard time doing so. In an example, say we wanted to show the process of a baking step in a recipe, by graphically counting down the minutes left the dough had to be in the oven. – how and here would get these informations if they were hidden in some chunk of text saying “now bake the dough for 25 minutes”. We might also want to search for recipes containing certain amounts of certain ingredients; a thing which also would be hard to do, with recipes just saved as chunks of strings.

“So, lets make an actual form, with an ingredient list, an ingredient-mixing step, a rising step, a baking step etc, so that we know more about the actual data being submitted”, I see the point in this approach, but I still think we might come in short by this approach. Recipes can be complex, and some might contain multiple baking steps, no rising step, etc. thus making it hard to limit the chief to a “one form fits all” approach. We could continue making the form more sophisticated and so on, but my point is of cause, that we should/could also consider thinking in terms of a Domain Specific Language; a language limited to the baker and recipe domain, with a limited expressiveness and with concepts familiar to the chief baker.

I’ll leave our bakery for now, the above case was primarily to get us into a solution-thinking-state-of-mind which we can leverage when going trough the following. By not giving my idea (not yet at least) of a solution to how we should solve the bakery application, I hope your own creativity will have more room for thinking of ways to create a fitting solution. – hopefully a solution which will be inspired by the DSL-road trip we are about to take.
I’ll now return to a more concrete talk about what a DSL is, the different types and how they can be implemented.

Different types of DSL’s
Generally DSL’s are defined in two main categories: internal DSL’s and external DSL’s. When talking about the types of DSL’s it is important to understand who the target audience is. Internal DSL’s are in my opinion more targeted technology persons (what an exact and concise definition :-) ). What I mean by this, as you will read in a moment, is that internal DSL’s always will be bound to some sort of development environment element(s) (this being a hosting general purpose language, an IDE or editor, a general purpose language compiler and limited syntax). Therefor I think internal DSL’s are in broad mostly relevant to people knowing their way around a computer, but not necessarily a developer . In comparison to internal, the external DSL is not in a host language, thus being without the constraints related to an internal DSL. An external DSL, is in my opinion very interesting in regard to end-users and non technical people with expertise in a domain. The external DSL category is also where the “visual diagramming languages” fits in.

Internal DSL
In short an internal DSL is a language written in a “host” language. By host you should understand the General Purpose Language being used to write an “abstraction” or DSL in. As an example it would mean an DSL written in ActionScript to provide a higher programming abstraction trough a specific set of domain “objects” (objects as in domain related terms and model interpretations) and limited syntax. The syntax limiting is always limited to the ways to go about in the host language. As you actually is writing ActionScript you are not able to do any new and fancy formatting, as it is to be interpreted by the same compiler as normal ActionScript. Though, often it is possible to use little tweaks to hide the underlying host language, or noise, more or less. As an example the following snippet our Starbucks order from above, written in an Startbucks DSL, written i ActionScript:

?View Code ACTIONSCRIPT
var latte:Coffee = new Coffee()
.size = CoffeeSize.GRANDE
.where = Consumption.FOR_HERE
.fat = FatContent.NON_FAT
.water = Water.NO_WATER
.temperature = 180
.type = CoffeeType.TAZO_CHAI_TEA_LATTE;

What you should notice is the use of multiple lines, all of them starting with a “.”. This way of chain the syntax together, and not breaking any compiler/language rules while still providing a better readability is called Method Chaining”. Method Chaining can be part of the way of achieving what is know as a Fluent Interface”. Fluent Interfaces is the concept of treating lines of code as sentences, like we just did with the method chaining above. I cant help thinking about how frameworks and API’s in general can benefit from the thoughts related to DSL’s and fluent interfaces. A great example of DSL (if you would argue that testing is a domain) and fluent interfaces is Test Driven Development with JUnit, Hamcrest and JMock, where your are able to create logical, readable constructs when writing your tests, by using method chaining and subsequent calls. See the example below:

public class MyTestCase {
    ...
 
    public void testSomething() {
        ...
 
        context.checking(new Expectations() {{
            oneOf (logger).error(with(aStringStartingWith("FATAL")));
        }});
        ...
    }
}

In the above we see how we can construct a human-readable string (at least a programmer-readable string) by using the syntax and method naming around the JMock and testing domain.

In regard to the Fluent Interface and Method Chaining there is a little advantage in ActionScript in our ability to write properties as getter/setter methods. This can help us remove a little more noise from our DSL. In practical terms we are able to change the “( )” with a ” = ” which is a more known operator for non developers; assigning a value on the right side to something on the left side. – like we did it in our Coffee example above. The trick in using method chaining and getter/setter, as you properly have figured out, is to let each setter return the containing object itself:

?View Code ACTIONSCRIPT
package
{
	public class Coffee
	{
		public function Coffee)
		{
			//...
		}
 
		public function set size(value:CoffeeSize):Coffee
		{
			//...
			return this;
		}
 
		public function set where(value:Cosumption):Coffee
		{
			//...
			return this
		}
 
	}
}

The Bakery internal DSL
We could argue that we should create an internal recipe DSL to our chief baker. This would of cause not be the best thing to do, as our dear chief baker might not be very familiar with computers when it comes to tasks outside the “normal use”-boundaries. But on the other side, that would just mean that we would have to be even more focused on providing a domain language to the chief that “feels at home” and hides away constraints and noise in our host language.
To remove this “host language noise” we will of cause use what ever tweak we can in our language, to make it more fluent.

The creation of a recipe, in our Bakery DSL could look like something like this:

?View Code ACTIONSCRIPT
 var r:Recipe = new Recipe
 (
 
	add(25).grams.of.flour,
	add(2).oz.of.water,
	mix(),
	add(2).kilos.of.sugar,
	mix(),
	rise(2).hours,
	bake(30).minutes.at(200).celcius
 
);

As you can see we try to make it very sentence like, by constructing expressions that look as close as possible to the way we actually describe a recipe in the real world; “Add 25 grams of flour”. The way I have achieved the above syntax in a language like ActionScript is by using the Proxy class in AS3, a factory, and a set of package methods.
I’ll in the following show how it is implemeted.

Here is my Bakery App project:

Recipe Class
The Recipe class, which constructor takes an unspecified list of ingredients and actions in the order they should be executed. This is done by using the “…” syntax in AS3. This way the handling of the various elements and steps constituting the recipe can be handled generic. As mentioned above one problem with static forms could be, that some recipes have multiple baking steps, and others none. By pushing a list of n’ in the constructor we are not locked to any order, or any special sequence. The implementation of what to do with the elements when they are received in the constructor is not of interest here, as much as HOW we go about and create the elements we want in a recipe.

?View Code ACTIONSCRIPT
package model
{
	public class Recipe
	{
		public function Recipe(...args)
		{
			//...
		}
	}
}

The Ingredient
Inside the constructor call of the recipe, we make use of a set of statements which starts with a “key word” related to an action in our domain. The first line, which will look closer at adds a new ingredient to the recipe:

?View Code ACTIONSCRIPT
add(25).grams.of.flour

What is actually created in this sentence is new instance of an ingredient object with 25 as the amount, grams as the measuring unit and flour as the name of the ingredient. The implementation of the ingredient class is shown below here. It is in it self not very interesting, but the interesting part is how we remove the noise of object creation from the language we want to provide, and make the syntax intuitive:

?View Code ACTIONSCRIPT
package model
{
	public class Ingredient
	{
		private var _amount:Number;
		private var _measureUnit:String;
		private var _name:String;
		//...
 
		public function Ingredient(amount:Number,measureUnit:String,name:String)
		{
			_amount = amount;
			_measureUnit = measureUnit;
			_name = name;
 
			//...
		}
 
		//...
 
	}
}

Package Method
So now we know how we should end up; with an ingredient object, with a measuring unit, an amount and an ingredient name. We start this process by calling “add”.
The add “key word” which is actually just a method declared in an ActionScript file in a package, can be used, everywhere as long as it is imported to the current file you are working in. It is like other methods like “navigateToURL” etc. already in the AS3 API. What I like about doing it this way, in stead of having a local add method in the containing class, is the separation. As you can see in the overview of the project, all the add, bake, rise, mix methods is in their own package.

This makes it easy to control what domain actions reside, and you don’t have to clutter the Recipe class or the class where you want to use the DSL by implementing all these methods there. So to say we delegate the responsibility of “catching the domain action” out to a separate method, instead of having this in a class. This also makes it easier to maintain if the implementation of certain method names or “domain actions” changes. And lastly, it gives a great overview, of the domain actions. – also in terms of collaboration with the domain experts, as the extraction and abstraction is very human readable.
The actual implementation of the “add” method (and most of the others for that matter) is a further delegation of control, to an appropriate factory class. Here is the implementation of the “add”:

?View Code ACTIONSCRIPT
package actions
{
	import util.IngredientFactory;
 
	public function add(amount:Number):IngredientFactory
	{
		return new IngredientFactory(amount);
	}
}

The Factory
As shown above, the “add” method delegates the amount passed in, to an “IngredienFactory” class. If we continue to look at our sentence under investigation, we see that the following is a chained expression of the measuring unit, and the name of the ingredient.
add(25).grams.of.flour
If we look inside our “IngredientFactory” we see that this is implemented by extending the AS3 Proxy, thus making our “IngredientFactory” dynamic, and open for any type of property call (gram, grams, kilo, kilos, oz, pieces, piece, …)

?View Code ACTIONSCRIPT
package util
{
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
 
	import model.Ingredient;
 
	dynamic public class IngredientFactory extends Proxy
	{
		private var _measureUnit:String;
		private var _amount:Number;
		private var _addingName:Boolean = false;
 
		public function IngredientFactory(amount:Number)
		{
			_amount = amount;
		}
		override flash_proxy function getProperty(name:*):*
		{
			var result:*;
 
			if(_addingName)
				result = new Ingredient(_amount,_measureUnit,name);
			else
			{
		 		_measureUnit = name;
				result = this;
			}
		 	return result;
		}
 
		public function get of():IngredientFactory
		{
			_addingName = true;
			return this;
		}
 
	}
}

As you can see I have made the “getting” of “of” the trigger, that assembles the amount, the measuring unit, and the name of the ingredient, and returns a new instance of an ingredient, with these arguments in the constructor. The is of cause based on the concordance that an “ingredient sentence” is always composed like:

<code>measuringUnit.of.ingredientName</code>

This concordance should of cause be derived from the domain (hence the domain experts). In this example I’ll not go deeper into the domain, but you could try to think about how you would create the ability to say something like “add(2).eggs” where there is no measure unit (or it is at least implicit in the sentence) and no use of the “of” keyword.

Besides the “add” method, I have in my example created methods like “mix”, “bake” and “rise”, and there could be many more. In our bakery domain they make perfect sense in the construction of a recipe. And we would now know when to tell the bakers to mix ingredients, when and how long to rise, and at what temperature the bread should be baked.

So to sum up the implementation pattern used;

  1. we subsequent the steps and ingredients as arguments to the constructor
  2. we create domain actions as package methods
  3. we delegate the creation of domain objects/concepts to a dynamic factory

As mentioned this is example is very staged and the point was not to show how to develop a bakery application, but to show how to abstract an API or Domain concepts inside a programming language, into a higher level DSL.

Outro on part 1
Pheew, boy was that a lot of words. I’m glad I decided to make this a series, otherwise I would never get to close up this blog post :-)
I hope you have gotten a glimpse of what a DSL is in general, and what a DSL is in terms of an “internal DSL”. I also hope you have gotten the idea of how you could create such an internal DSL in ActionScript by using some of the great dynamic possibilities we have at hand.
In terms of internal DSL’s AS1/2 was actually even more dynamic with its implicit declarations and weak typing. These qualities (though people often do not look at them as qualities) is some of the things people value in Ruby, which is gaining momentum these days, as a language for writing internal DSL’s.
In the next part on the subject I’ll be taking closer a look at external DSL’s and how we with Rich interfaces can create visual DSL’s to use for the domain experts.

ActionScript, Business Domain, DSL, Use Cases , , , , ,

Through the mouth the heart speaks

December 9th, 2008

I guess the title is very much how I hope this blog will turn out. For some time now (years actually) I have wanted to get my personal blog going. Even though I have tried setting up wordpress or other blog-featuring CMS’, I have never managed to get passed that initial “Hello World” post. – so here goes.

Getting past that “hello world” post
I guess that my lack of bloggin is due to a great involvement in the Danish online RIA community FlashForum which I am co-managing. Besides taking a lot of my time, writing tutorials, articles and helping people out at the forum onthe community site satisfy my urge to write. But still I have decided to give the personal blog a tryout.

Why go for more?
In the year passed, the need for a textual sanctuary has emerged; a place for me to geek out, and let the mouth speak what fills the heart, has been needed. So I hope this blog will give me the “lungs of the city” that I have longed for.

I’m looking forward to an exciting time here, on my own playground :-)

Uncategorized