Flex Best practices. Sketch 1: An application with a single Event class

This is the first of the series of articles that Flex architects from Farata Systems will be posting over the next several months. We “ll introduce you to our own class library that goes by a working name theriabook. Over the last couple of years we “ve been successfully using various coding techniques and custom components that turned the application development in Flex into a RAD project.

I “ll start with some history and definitions. While working on the book “RIA with Flex and Java rdquo;, we “ve been building a library of reusable components for the book samples. Since the book writing was our moonlight activity, we “ve had a chance to try all these components at the battlefield ndash; during our consulting gigs with various clients. Unfortunately, last week we “ve had to politely reject the offer of our publisher, Sys-Con Media for writing the second edition of that book. We just do not have time. So if you are thinking of purchasing a copy, do it sooner than later – it “ll be gone soon.

There are three ways of writing software:

1. Just write the code from scratch

2. Pick a framework and write the code by the rules dictated by this framework

3. Use selected components from one or more class libraries

To see the difference between a framework and a class library, visualize a construction site of new housing development. In one home site, you see a frame of the future house, rooms are laid out, and electrical wire are hanging everywhere . The site next to it just has a pile of construction materials ndash; Anderson windows, 2X4th, et al. Of course, the latter gives you a lot more freedom as to how your future house will look like hellip;as long as you know how to construct it.

We like freedom, and will be presenting not only our “Anderson windows rdquo;, but also instructions for using them during construction of your application. Best practices, as we currently see them. Your input is greatly appreciated and if you have your own construction materials or tricks of the trade, please add them to our pile.

All objects from our theriabook library will be available for free as an open source software governed by the MIT license ndash; the same as Flex framework.

Without further ado, let “s go to our first best-practice.

An Application With a Single Event Class

Flex is all about event-driven development. Create loosely coupled objects and let them send events to each other. You can read about this in the following blog

In a nutshell, you can create new events for every occasion you need. If an event does not need to carry any additional data, just extend flash.events.Event, and define the meta-tag to help Flex Builder listing this event in its type-ahead prompts and dispatch it when appropriate. If your new event needs to carry some data, create an ActionScript class, define a variable in your subclass to store your data, and override the method clone();

If we take a mid-size Web site with 10 views, where each view has two components that can send/receive two events, you can quickly rich forty or more custom Event-based classes that look pretty much the same. To ensure that the situation does not go out of control, some of the Flex frameworks force you to register upfront each event in a central location.

We say, “No need to do it. You can get away with one event rdquo;. So a sample application below has only one defined event class that can fit multiple purposes without the need to introduce tight coupling between your application components.

To illustrate the concept, I “ve created a simple application that looks as follows:

This application consists of two modules (GreenModule and RedModule) that are loaded in the same area of the main application on the click of the appropriate Load button. It also has one universal event class called ExEvent. If you click on the Send buttons, an instance of this event is created and you can put there an instance of Object, a DTO, a couple of string variables, nothing, or anything else you like. In this example I “m using a DTO class called GirlfriedDTO.as. There is no mapping between the event you send and the modules. For example, if you send a Green event to the Red module, nothing happens since the Red module is not listening to the Green event.

I “ve been using modules in this application not because I endorse them, but rather because they give me a chance to quickly illustrate a concept of run-time loading and lose coupling between the objects and events. Victor Rasputnis, my colleague at Farata Systems has been experimenting with modules and next month will publish an article describing his findings.

A completed application and its source code is deployed at this URL. Its Flex Builder “s project has a folder modules that contains two modules ndash; red and green. The red one is listening for the arrival of the girlfriend “s first and last name packaged in our single event class as two separate strings:

lt;?xml version= “1.0 ” encoding= “utf-8 “? gt;

lt;mx:Module xmlns:mx= “http://www.adobe.com/2006/mxml ” layout= “absolute ”

width= “100% ” height= “100% ” creationComplete= “onCreationComplete(event) ” gt;

lt;mx:TextArea id= “display ” backgroundColor= “#FF4949 ” width= “100% ” height= “100% ” fontSize= “28 “/ gt;

lt;mx:Script gt;

lt;![CDATA[

private function onCreationComplete(evt:Event):void{

this.addEventListener( “RedGirlfriend “, onRedGirlfriend);

}

private function onRedGirlfriend(evt:ExEvent):void{

display.text= “My girlfriend is “+ evt.fName+ ” ” + evt.lName ;

}

]] gt;

lt;/mx:Script gt;

lt;/mx:Module gt;

The green module expects girlfriend “s name in a form of GirlfriendDTO:

lt;?xml version= “1.0 ” encoding= “utf-8 “? gt;

lt;mx:Module xmlns:mx= “http://www.adobe.com/2006/mxml ” layout= “absolute ” width= “100% ” height= “100% ”

creationComplete= “onCreationComplete(event) ” gt;

lt;mx:TextArea id= “display ” backgroundColor= “#9CE29C ” width= “100% ” height= “100% ” color= “#070707 ” fontSize= “28 “/ gt;

lt;mx:Script gt;

lt;![CDATA[

import dto.GirlfriendDTO;

private function onCreationComplete(evt:Event):void{

this.addEventListener( “GreenGirlfriend “, onGreenGirlfriend);

}

private function onGreenGirlfriend(evt:ExEvent):void{

var myGirlfriend:GirlfriendDTO=evt[ “girlfriend “];

display.text= “My girlfriend is “+ myGirlfriend.fName+ ” ” +

myGirlfriend.lName ;

}

]] gt;

lt;/mx:Script gt;

lt;/mx:Module gt;

The GirlfriendDTO is located in the folder dto and is pretty straightforward too:

package dto

/**

* This is a sample data transfer object (a.k.a. value object)

*/

{

public class GirlfriendDTO

{

public var fName:String; // First name

public var lName:String; // Last name

}

}

Now let “s talk about our single but universal event class. It “s based on the DynamicEvent class, which allows you to add any properties to the event object on the fly. Surprisingly, Flex documentation discourages you from using this class. Here “s what it reads:

This subclass of Event is dynamic, meaning that you can set arbitrary event properties on its instances at runtime. By contrast, Event and its other subclasses are non-dynamic, meaning that you can only set properties that are declared in those classes. When prototyping an application, using a DynamicEvent can be easier because you don ‘t have to write an Event subclass to declare the properties in advance. However, you should eventually eliminate your DynamicEvents and write Event subclasses because these are faster and safer. A DynamicEvent is so flexible that the compiler can ‘t help you catch your error when you set the wrong property or assign it a value of an incorrect type.

Let me respectfully disagree with this recommendation and suggest you to use the dynamic nature of this event not only for prototyping, but also for development and deployment of your applications. When GUI components send event to each other, the difference in the processing of your dynamic vs. static event instance is negligible. It “s not clear how safer the static event are. I do not think so.

When you design an event-based interaction between components of your applications, both the sending and receiving parties must know in which format the data are being delivered by an event. And we utilize this knowledge even in case of the dynamic events. We can use either a well defined GirlfriendDTO:

var myDTO:GirlfriendDTO=new GirlfriendDTO();

myDTO.fName= “Mary “;

myDTO.lName= “Poppins “;

var greenEvent:ExEvent=new ExEvent( “GreenGirlfriend “);

greenEvent.girlfriend=myDTO;

someObject.dispatchEvent(greenEvent);

or just add two string variables:

var redEvent:ExEvent=new ExEvent( “RedGirlfriend “);

redEvent.fName= “Mary “;

redEvent.lName= “Poppins “;

someObject.dispatchEvent(redEvent);

In this sample I use an ExEvent, which is a subclass of the DynamicEvent ndash; it just has a little enhancement that eliminates manual programming of the property Event.preventDefault:

package

{

import mx.events.DynamicEvent;

public dynamic class ExEvent extends DynamicEvent

{

private var m_preventDefault:Boolean;

public function ExEvent(type:String, bubbles:Boolean = false,

cancelable:Boolean = false) {

super(type, bubbles, cancelable);

m_preventDefault = false;

}

// It ‘s an enhancement: DynamicEvent class does not

// automatically process preventDefault in cloned events

public override function preventDefault():void {

super.preventDefault();

m_preventDefault = true;

}

public override function isDefaultPrevented():Boolean {

return m_preventDefault;

}

}

}

Now the code of the test application loads modules, and then the user can send any event to whatever module is loaded at the moment. Of course, if the currently loaded module does not have a listener for the event you “re sending, tough luck. Do not expect miracles ndash; nothing will happen. But the good news is that it won “t break the application either:

lt;?xml version= “1.0 ” encoding= “utf-8 “? gt;

lt;mx:Application xmlns:mx= “http://www.adobe.com/2006/mxml ” layout= “vertical ” viewSourceURL= “srcview/index.html ” gt;

lt;mx:HBox gt;

lt;mx:Button label= “Load the Green Module ” click= “loadMyModule( ‘modules/GreenModule.swf ‘) “/ gt;

lt;mx:Button label= “Load the Red module ” click= “loadMyModule( ‘modules/RedModule.swf ‘) “/ gt;

lt;mx:Button label= “Send Green Event with Object ” click= “sendGreen() “/ gt;

lt;mx:Button label= “Send Red Event Event with two strings ” click= “sendRed() “/ gt;

lt;/mx:HBox gt;

lt;mx:Panel width= “100% ” height= “100% ” title= “A module placeholder ” layout= “absolute ” gt;

lt;mx:ModuleLoader id= “theModulePlaceholder ” width= “100% ” height= “100% “/ gt;

lt;/mx:Panel gt;

lt;mx:Script gt;

lt;![CDATA[

import dto.GirlfriendDTO;

//Load the module specified in the moduleURL

private function loadMyModule(moduleURL:String):void{

theModulePlaceholder.url=moduleURL;

theModulePlaceholder.loadModule();

}

// Sending generic ExEvent adding an object that contains

// the name of the girlfriend

private function sendGreen():void{

// Strongly typed DTO – better performance and readability,

// but its structure has to be known for both parties –

// the main application and the module

var myDTO:GirlfriendDTO=new GirlfriendDTO();

myDTO.fName= “Mary “;

myDTO.lName= “Poppins “;

if (theModulePlaceholder.child !=null){

var greenEvent:ExEvent=new

ExEvent( “GreenGirlfriend “);

greenEvent.girlfriend=myDTO;

theModulePlaceholder.child.dispatchEvent(greenEvent);

}

}

// Sending a generic ExEvent that holds the name of the girlfriend

// as two separate variables

private function sendRed():void{

var redEvent:ExEvent=new ExEvent( “RedGirlfriend “);

redEvent.fName= “Angelina “;

redEvent.lName= “YouKnowWho “;

if (theModulePlaceholder.child !=null){

theModulePlaceholder.child.dispatchEvent(redEvent);

}

}

]] gt;

lt;/mx:Script gt;

lt;/mx:Application gt;

The function sendGreen() sends an instance of our ExEvent event with DTO, while the sendRed() just adds two properties fName and lName to the instance of the ExEvent.

Instead of using a well defined DTO, I could “ve used a weakly typed data transfer object:

var myDTO:Object={fname: “Mary “,lname: “Poppins “};

But this would result in poor readability of the code and a bit slower performance. On the positive side, there would be no need to explicitly define and share the class structure of the dto between the app and the module. I “d do something like this during the prototyping stage, but not in a real code.

Let “s recap. What did we gain? No need to create lots of tedious coding defining dozens of similar event classes. What did we lose? Since we did not use the metatag Event declaring the names of the events those never declared event classes, Flex Builder won “t be able to help us with the name of the event in its type-ahead help. No biggie.

In the unlikely case if there is a view in your application that can “t afford to lose a couple of milliseconds caused by using dynamic event, use static but in that view only. But with a single dynamic event the code base of your project will become smaller, and more readable.

American sketches: ER and neighbours

Sunday evening, my younger son comes to the kitchen complaining about the pain in the right part of his belly.We suspected appendicitis, but decided not to spend a night in the ER. Our next door neighbor is a physician who works in the ER. We did not even think of knocking at his door. America practices protective medicine, which means that a doctor ‘s main goal is not to get a law suit. We knew that he would not give us any advices other than going to ER.

Today, my wife went to our pediatrician, she also suspected appendicitis and told my wife to take my son to ER immediately. She did. To their pleasant surprise, they saw our neighbor in the ER. He gave her a warmest hug and a kiss (they did not talk to each other foe several years – this is how the neighbor live here. She was really happy to have an insider in the ER. He said to my son, “Do not worry, it ‘ll be fine “.

My wife recovered after the hug, and asked the physician, if he might have an idea what can be the diagnosis. He answered, “Do not worry, the nurse will tell you everything. ”

He was afraid to say anything even in ER! Hug and kiss do not mean anything, but he wants to stay out of troubled for giving the wrong advice. That ‘s why we did not even think to ask a neighbor physician for help in the first place. America 😦

Staffing a team for your Flex project

At the end of 2006 I wrote in a blog that Flex programmers should sit tight, improve their skills and wait till 2008 ndash; the year of their fame. The year of 2008 is here, and Flex people are in big demand. Two years ago, Flex community was more of a ghetto where most of the Flex programmers knew each other, but situation is different now. The number of Flex programmers is increasing, and this population evolves similarly to what I “ve seen in the Java camp in the past.

The main concern of any project manager is if there are enough people in the pool of Flex developers to staff the project. Yes, there is a pool of Flex developers, but let “s look at the creature called “Flex Developer rdquo; under the microscope.

Presently, I work for two clients from different industries; both projects are redesigns of existing Java applications. One project has a small number of Flex screens but very serious requirements for the communication layer. The other project has lots and lots of screens with LCDS on the back. Both projects require three types of Flex personnel:

1. Flex GUI developers

2. Flex component developers

3. Flex architects

The first group is people who can create the view portion of the application. This is the easiest group to get into if you already have some programming language behind your belt. The rumors about high consulting rates plus work of educators and technical evangelists create an impression that working with Flex is easy ndash; just drag and drop components on the screen, align them nicely and write the functions to process button clicks or row selections in the data grid. Sort of a Visual Basic of the Web. These skills are easy to obtain, and you can expect a crowd of people there, but do not expect high pay rates in this segment. If something is easy to learn many people can master it, and savvy project managers either outsource this job to a third-part vendors or send their own developers to a one-week Flex training class.

GUI developers interact with Web Designers that come up with the look and feel of the screens, which can be presented as a wireframes created in Photoshop, some third-party tool or even in Flex itself. But even in the latter case, GUI developers should not start implementing screens until approved by a Flex component developer or an architect.

While this is a right way to start Flex career, you definitely should consider moving to the second group and become a Flex component developer. This title is awarded to people who know everything that GUI developers know plus object-oriented and event-driven programming. Knowledge of design patterns helps, but be careful here. Especially it applies to people coming from the Java world. Do not abuse MVC. Think out of the box. A screen created by a Web designer has to be scrutinized and redesigned into a set of components that communicate with each other. Applying the Mediator pattern to the initial wireframe is a good start as I “ve described in this blog .

Also, keep in mind that even though the syntax of ActionScript 3 looks very similar to Java, it has provisions for dynamic programming and you might not need to create tons of well defined objects as in Java.

The third group of people knows everything the first two groups plus they can see a big picture. They know how to build the entire application, how to communicate with the mid tier, how to structure your project, and how to make communication between reusable components, views and the persistence layer the most efficient. Flex architect are people who “d never suggest using a framework for creation a simple Video player as done in this blog. You do not gain these skills after a week of training, but you build them on top of your prior experience in other programming environments and by constant studying.

Not every Flex developer can be profiled as a member of one of these three groups. In smaller teams, one person may wear two hats: a component developer and an architect. If your team has decided to use one of the frameworks on top of Flex framework, you may wind up with a new type of team members that can be called framework coders. In this case it is assumed that this XYZ framework provides a structure that will take care of inter-communication between components, and coders just need to put their model, view or controller objects into the right directories, buy popcorn, press the button “Play rdquo; and watch the movie. This may or may not work as expected, but you may find out about it later in the game. If you are not lucky and the film got stuck in the projector and caught fire well into the movie, get ready to ask for an extra budget for a new project called “Removal of the XYZ framework rdquo;, which reminds me of a good old joke.

A poor man comes to the rabbi complaining that his family has only one small room, many kids, and almost no money. The rabbi says, “Take all your money, buy a goat, and keep the goat in your room. Come back in a month. ”

“But, rabbi, we don ‘t have enough space even for us, ” the man said

“Just do what I say, ” the rabbi replied.

A month later the man comes back complaining that the goat smells and breaks everything.

“Sell the goat and come back in a month, ” the rabbi tells him.

A month later the man comes back to the rabbi with flowers.

“Thank you, rabbi! We ‘re so happy the goat is out, now we have more room and some money from selling the goat! ”

If you are considering adding Flex to your set of skills, it “s still early in the game and you can join the fast growing Flex community. Decide which group of the Flex developers looks most appealing to you. Set a goal and go for it. Be what you can be.

Do not turn Java into C++

When I run into yet another posting about adding yet another cute little element to Java syntax, it makes me sad and angry. It seems that people are converting Java into a some kind of a science project.

Someone asks, “Kids, what new features you ‘d like us to add to Java language? ”

And the chorus responds, “We want this, we want that…And we want it now! ”

“OK kids, we ‘ll give you this and we ‘ll give you that. We can ‘t give it to you now cause we have a process. We ‘ll run experiments on humans, and if not too many software developers will stop using Java because of these new features, we ‘ll stick them into the language spec. ”

We had a nice language, then it became a platform, then for some people it became a religion. Some time ago I was trying to participate in various Java forums. But then I realized that if you are not 100% for Java, some of them become dangerous places to be. If you even mention any other language that people are using behind the fence (should I say behind the iron curtain?) you become an enemy.

And the closures discussion is a pinnacle of what can be done to screw and bury Java. Closures are discussed by the best minds in the community, but when I look at the proposed syntax, I get an impression that these best minds are flying so high, that they do not have time to see how these closures are implemented in other languages. While the trend in other languages is to hide the complexity by engaging under-the-hood-code-generators, Java closures proposals are forcing a programmer to do all the calligraphy.

JavaFX is an a little-to-late response from Sun to the rapidly growing community of the languages, tools and techniques for development of the rich Internet applications. Fine, let ‘s give JavaFX some time, it ‘s still too young. But what can you expect from a scripting language built on top of Swing libraries? This is already outdated…even before its own release. I hope to see some real competitive sample applications showing the power of JavaFX rather than declarations that it ‘s a Flash or Silverlight killer. This is not even funny.

JVM is very robust. Why not concentrating major efforts on Consumer JRE, Java Kernel, creating new languages that can run on JVM?

Java as the language is pretty stable in the server-side enterprise applications. A typical IT shop of a large firm in the USA is either Java or .Net.

You may argue that J2EE is too heavy and will be replaced with “lighter frameworks “, but in the end, it ‘s still Java. You may not like the fact that Google ‘s Android is not using Java as the doctor ordered, but hey, it ‘s still Java.

Even without any new additions Java is not going anywhere and we can safely retire developing applications in this great language. The Java bookshelves are already shrinking in size, which is clear indication that less people are interested in this language. Please leave the Java syntax alone. KISS.

Answering James Goslings Flash Player Comments

Redmond Developer News has published an interview with Dr. James Gosling, creator of the Java language where among other things, he talks about JavaFX and competing technologies. And he made a comment I can “t agree with. Here “s the quote from that interview:

“As organizations think about building rich Internet applications or rich client applications, when should developers look at JavaFX over competing technologies?

If you look at something like Flash, when you get to the much more advanced stuff — richer interfaces, more complex network protocols, more complex APIs — it really falls short. We ‘ve had a platform for years that can build rich Internet applications that are extremely sophisticated. rdquo;

Before even going to technical details explaining why this statement is wrong, let me tell you that if someone would ask me to name a dozen of the most respectful people in the industry, James Gosling would be one of them. Because of him, I live in a nice house and drive a nice car ndash; I “ve been doing Java for the last ten years. If James would not invent Java, I “d be probably still working with PowerBuilder writing that it “s the best thing since sliced bread.

But let “s go to the essence of the accusations. Dr. Gosling does not attack the presentation and delivery abilities of Flash Player because Flash Player is today “s leading delivery mechanism for rich Internet applications. He addresses network protocols, something that may not be as easy to argue. So let “s talk protocols.

In 2007, my colleague and I were invited by a financial company (a Java shop) to assess if they could create an Internet version of their trading application using Flex. They did not have any doubts the GUI part should be done in Flex and delivered to their customers by Flash Player. Using AJAX for such an application would be crazy.

Sun “s long history of ignoring Java as platform for delivering Internet applications ruled Java applets out. A dancing Duke made his short appearance in 1995 and was forgotten by Sun for the next 10 years. Can you imagine Amazon or Google using Java as a front end for their applications? It “d be insane ndash; they “d lose a half of their customers trying to persuade them to use Java applets – each of them had different version of JRE and installing the right one required a college degree in computers. I hope this situation will change with the introduction of Consumer JRE later this year, but we are not there yet.

Anyway, this financial company was not sure if the communication protocols offered by Flex were robust enough to provide reliable and guaranteed message delivery and could be extended to accommodate specific needs of this application, such as adding the application-specific quality of service (QoS) information right to the packages sent over the network from the Flash client to Java server-side application. They wanted some other things too, such as message throttling in case of network congestion and more.

Flex offers a server-side piece called LiveCycle Data Services ES, which comes with a couple of fast communication protocols: AMF ndash; a binary protocol that makes calls over HTTP from client to server (polling) and RTMP ndash; real time messaging protocol that supports real time push from the server to Flash client. By the way, AMF goes open source in a month or so (see BlazeDS). Java offers RMI protocol for RPC and JMS for messaging. RTMP is easy to integrate with other messaging systems via JMS. Security is similar to Java applets (sandbox) and you can use RTMPS instead of RTMP.

Under the hood, AMF and RTMP protocols implement object serialization, so an instance of a Java object gets serialized on one end and is recreated as an instance of the ActionScript object on the client inside Flash Player, which is nothing else but a VM. On the way back, an ActionScript object is serialized on the client and gets recreated in the server “s JVM as a Java object.

One of the most important features of the Flex framework is that it “s extendable. The server side of implementation of these protocols is written in Java, and the client side in ActionScript 3. To make the story short, we were able to extend the communication channels, end points, message consumers and producers to enrich RTMP protocols to the clients specification. Now the messages about trading orders and executions travel happily between the Flash client and Java server. Security is similar to Java applets (sandbox) and you can use RTMPS instead of RTMP.

This project was an example of a nice marriage between Flex and Java in a Wall Street application. If Flex has weak spots, it “s slow compiler and a mediocre (by Java standards) Eclipse-based IDE . Since Flex is open sourced now, I hope that some third-party company will create a better IDE and improve the compiler.

But as of now, I “m pretty happy with using both Java and Flex technologies, and the good part is that it “s not an either-or situation ndash; just use the right tools for the job. There is no need to lobby for any particular language. As to JavaFX, I wish it to start competing with Flex and Silverlight as soon as possible. The more the merrier.

Some time ago I said to my kids, “Even if, God forbid, you “ll commit a crime, Mom and I will still love you and will try to protect you to the very end. You are our kids and we love you regardless of your achievements and personal qualities rdquo;. It seems that James Gosling has the same principles and protects his baby no matter what. I respect this but have my reservations.

James Gosling ‘s fan,

Yakov Fain

Time Magazines 50 best Web sites

Time magazine has published their version of 50 best Web sites of 2007 . Check it out. You may or may not agree with their ranking, but I ‘m sure you ‘ll find some interesting sites there that you did not know about. All these sites are Web2.0-ish, which by my definition are not the sites that were built using any particular technology, but rather the sites that give more control to the end user. So while some people say that Web 3.0 is about semantic Web, I believe that Web 3.0 sites will just give the end user more control than Web 2.0 ones.

But since developing rich Internet applications is my main professional activity, I could not stop myself from looking what ‘s under the hood at the Time ‘s Web site.

It ‘s good to see that they are gradually introducing Adobe Flex to their Web site. While most of the Web site is done using DHTML, the widget that shows “Top 5 Best Web Sites ” is done in Adobe Flex. Just right-click on that area and you ‘ll see that it was delivered by Flash Player. To be more specific, most likely it ‘s a custom component that consists from a VBox container (a box with vertical layout) that in turn has an HBox and a DataGrid. The HBox holds the Label that reads Top 5 Best Web Sites ” and two buttons – one is a button with an image Refresh Data and the other one is a button with a custom skin that looks like a circle(?). As you move your mouse over that button, you ‘ll see a tooltip that shows you a hint that the DataGrid below is sortable – just click on the column ‘s header. If Time developers read this blog, I ‘d appreciate if someone would confirm that I ‘ve guessed your Flex components selection correctly.

I applaud Time for using Flex. Just think about it, this little widget that displays the rating can be coded in no time – one hour for coding and testing and one hour for the skin creation, which can be done in parallel by a Web designer in Photoshop. The speed of development is crucial for any multimedia mega site such as Time magazine.

Of course, since they are just starting, there are some usability issues, for example if you sort the ratings table by any other than Rate column, the text of the Label above should change from “Top 5 Best Web Sites ” to something else based on your sort criteria.

Another usability issue – there is a column Total Votes, but it ‘s not clear how the user can vote. I ‘d use a custom item renderer in the Total Votes column to turn the number of votes into a clickable link that would bring the user to the voting page. In Flex, this would take another 5 lines of code.

But these are the little things that will be ironed out in the future. Good job, Time Magazine! Go Flex!

Update. One of the readers (thank you, Zohar) gave me a reference to a Web site created by James Ward to check if a site was created in Flex

http://www.jamesward.org/is_it_flex/

If you try this URLhttp://www.time.com/time/flash/time50BestWebsites/top5/top5_websites.swf you ‘ll see that the site was not created in Flex. Oh, well, at least it ‘s ActionScript 🙂 Time, go Flex!

Do we need third-party Flex frameworks?

This started as a Skype chat room conversation between my colleague Anatole Tartakovsky and myself, and I thought that it would be a good idea to invite more Flex developers to this discussion.

Having said this, I “d like to make it clear that over my career, I “ve been developing frameworks and truly respect people who are capable of creating frameworks, and Anatole has huge experience in this area as well. Here we “re just questioning the need to create frameworks not for a general-purpose language like Java, but for a domain-specific framework like Flex.

This is our dialog with minor editing. Your input and feedback are greatly appreciated.

Yakov: Why do people design Flex frameworks as opposed to reusable components? One of the framework is called Cairngorm, the other one is called PureMVC. I “m sure there is more. It seems to me that such frameworks are unnecessary overhead over well-designed Flex frameworks. Are there any benefits here? Why bother creating all these singleton-based bottlenecks?

Anatole: First of all, PureMVC seems to be more of an ActionScript Framework. It is not specifically a Flex framework and concentrates on the task of creating a generic framework for low-level AS objects. Flex comes with “prebuilt suggestions rdquo; of how a model/view controller might work – and it offers lots of hooks throughout the data and UI classes that help implement MVC.

PureMVC is also “server-agnostic “. Flex made the Java implementation of a distributed Model that can provide dynamics to the distributed Web applications very efficient. PureMVC is more about making apps in a more traditional way.

Cairngorm was started as “Micro ndash; Architecture rdquo; ndash; a set of patterns that allowed the solving of certain problems in the application design ndash; like Model Locator or Commands ndash; and certain applications. It never appealed to me as it had a number of assumptions that required more coding. At best you would use one or two pattern implementations from Cairngorm, but it “s much easier to rip out the part you need and adjust it to your liking.

Yakov: I can appreciate the fact that design patterns are useful in general, because they may help developers deal with repeating patterns in software constructions such as Singleton, Mediator, Model-View-Controller and the like. But when I look at some of the third-party frameworks built on top of Flex, I keep asking myself the same question, “Why build a framework on top of a framework? Are there any benefits to introducing a middleman between an application ‘s views and an already existing Flex framework?

Anatole. It depends on the application you are building. Frameworks provide higher level of automation and abstraction for specific tasks and with various coding and performance costs. Fo example, Flex framework has Data Management Services for distributed Web applications. However, this model has limited applicability for simple Web applications working with HTTP forms-based backend API. You “d need a symmetrical MVC API on the client side. You can also have a client-side only text editor application, for example, that is completely “out of scope rdquo; for Flex framework but would benefit from implementing a Command pattern. The real question is to identify the functionality you need, and then to see how it is implemented in the appropriate framework

Yakov. I looked at the Cairngorm “s design, and having hard times figuring out why would I need something like this? Ok, you may say that it helps to organize your project better. What else? Without any disrespect to creators of Cairngorm, I can ‘t find a justification to recommending it to my clients. One of them has invited me to lead an ongoing Flex project, which is being developed by a large team of developers. The project uses Cairngorm, and at the same time it consists of a number of modules. After reviewing the project, I ‘ve recommended to stop using Cairngorm. Without going into details, these are some of my concerns in this case:

The client wants to use modules, which are can be loadable/unloadable. But since you are forced to use Cairngorm ‘s singleton model locator, it ‘ll keep the hard references to the modules (event listeners), which won ‘t allow you unloading modules. So, on top of Flex modules ‘ memory leaking (yes, they leak), we ‘d introduce another memory issue.

Anatole. In many cases, a detailed look at the implementation will either get you on board or will remove the framework as not applicable implementation. In later releases of Cairngorm you can have weak references – so it works – at least theoretically. However, with modules there are quite a few places when unloading will become impossible due to legitimate code generated by framework. In general, if you are going with modules, you need multi-layered framework and intelligent registration services that are written specifically for the task.

Yakov. As far as I know, the use of Cairngorm was never approved by Adobe Flex team, but I might be wrong here. Flex framework is built on a nice distributed event-driven architecture, but Cairngorm is forcing your events to go through another singleton – event dispatcher. Why is that? Why every view has to register event listener in a central place? Now developers on a large project have to acquire additional skills in proper usage of this framework.

Anatole. The reason for use of global event listeners registration are derived from the size / type of applications the framework developers worked with. It “simplifies ” the project management by providing structure and separating developers responsible for model, view and controller into separate entities. All these singletons and managers are a way to establish a non-UI but business communication between parts.

Yakov. Do we really need global areas? Why not doing it locally when needed?

Anatole. First, you need to look at the events. In most cases, these are not UI or input events but rather some application/state changes that need processing. The model is global, and the application events are defined on the global level.

I think most of the seasoned developers with UI background are uncomfortable with this approach. You might want to consider Joe Berkovitz MVCS approach as a middle ground between Cairngorm and our component-based approach that might work better for medium to large size teams that would have no access to code generators and data driven/factories-based architecture.

I recall two framework-related sessions at MAX “07, where approximately the same number of people were asked the question: how many of you have looked at Cairngorm? 70% -80% raised their hands during the Flex frameworks BOF session and 90% on the Best Practices session. During the Flex framework session people were asked a second question, ” How many of you would use or actively oppose Caingorm? ” This time they “ve got a 50/50 split.

Yakov. I hope to be able to attend MAX 2008. So all these people came to the Best Practices session to get reassured that they are doing the right thing? But I “d really want to see some concrete examples where using these frameworks would bring technical benefits. I want to stress, I ‘m not talking about self-contained components that would automate some tedious job but a framework on top of Flex Framework.

Anatole. I think the main benefit of any pattern library will be based on its applicability to your application. There are quite a few applications ndash; including infamous “shopping cart rdquo; ones ndash; that can be coded quite efficiently with any of these frameworks. On the other hand, the extra setup code provided for “flexibility rdquo; is ironically the least flexible part of it.

As far as benefit ratio between an architectural framework and smart components, I think you might want to try a little test. Ask any developer if she wants an architectural framework that still would require her to implement a DataGrid componment (she would be allowed to use Grid component or some other low level controls as a superclass). On the other hand, offer her a DataGrid component without any framework. I think this developer would recognize the importance of smart objects and go with a DataGrid. Take it a level deeper and you will see an “extra rdquo; code in a DataGrid , and we “ve successfully have overridden it in our own DataForm, SuperGrid and controls.

Yakov. Do not forget though, that we are enterprise developers and are mostly concerned with a boring thingy called data processing. There are legions of Flex developers who do not care about the DataGrid. They are into creation of cool visual components. But these guys do not need any frameworks either.

Here ‘s another strong statement from the PureMVC framework, “The PureMVC framework has a very narrow goal. That is to help you separate your application ‘s coding concerns into three discrete tiers; Model View Controller “.

But isn ‘t this goal already achieved in Flex Framework? Wouldn ‘t a simple separating views, controllers and models into different folders of your project suffice? In many cases the role of Controller in Flex is kind of blended into model itself (bindable data collections can emit and listen to events caused by some data changes). In some cases, if your application ‘s views have reusable business logic (i.e. validation or connection to specific back end data feed) you may create separate controller classes that may be shared by more than one view. But this should be done on the case-by-case basis, and not as a must for the entire application.

Here ‘s another statement from a well-written PureMVC documentation: “Making separation of Model, View and Controller interests eliminates the most harmful responsibility misplacement issues that hamper scalability and maintainability “. My English is not good enough to understand this phrase in its entirety, so can you play the PureMVC advocate and suggest, how PureMVC would improve Flex scalability and maintainability?

Anatole. Well, there is an old saying that life is a play, written by God, and directed by Devil. By making the process more formal you can build a lot smaller chunks, communicating and specific way, and in your mind the more formal process will yield better maintainability. On the other hand, it will create more parts to maintain and less flexibility to do so.

Yakov. PureMVC uses mediators, which is a very applicable pattern for the software that produces UI. But would it be that difficult for developers or project architects apply Mediator pattern while designing their business applications as opposed to relying on a framework that implements Mediator globally? Check out this blog on using the mediator. Is it that difficult so it has to be hidden into a framework?

Anatole. ActionScript 3 makes a lot of patterns excessive. A lot of things can be done by using events or dynamic code without really breaching good programming practices. One-liners work for me as long as they are simple and concise.

The main question remains, “Do you want to use intelligent objects that encapsulate most of the framework functionality or if you prefer to deal with simple objecst and do explicit coding for each instance? rdquo;

Yakov. I prefer using self-contained loosely-coupled objects.

Anatole. So, coming back to your question of system-wide singletons hellip; I do not see any reason for creating global objects – they are really bad for both application development process and maintenance in the long run. You can have a singleton pattern inside the models themselves or bind location services with module loaders depending on the architecture of your application.

I have seen these frameworks being used mostly as means to provide project manager/architect with ability to separate areas for developers, quantify functions and make project more manageable. The effect for the resulting application most likely to be negative, but it is very straightforward approach to build systems.

Yakov. So you are saying that utilizing a framework on a project allows create and enforce a nice looking project plan that reads, “Mary will create 10 model objects by February 1, and John will be done with his views a week before? ”

Anatole. Yes, and then we will have all the commands coded a week after that and then we will think about fitting it all together, essentially moving real architectural and design questions toward the end of the project. If you answer the question “How? rdquo; first, people tend not to ask “Why? rdquo; for quite some time. On the flip side, you will have people doing their parts rather quickly thus producing enormous amount of code to fix when the design problems become evident. The problem with formal coding techniques is the human generated code (thus cut/paste errors) without the ultimate understanding how it will be used and very little testing done while writing the code.

Yakov. In the USA, we are already accustomed to protective medicine, when the main goal is to ensure that the patient won ‘t sue you. So when a guy with a headache shows up in an emergency room, they start with sending him to an MRI and making tons of other not too necessary tests. But, it “s better to be safe then sorry… The same rationale here – it ‘s easier to CYA with a nice project plan (see http://www.acronymfinder.com for the definition of CYA).

Anatole. The problem starts MUCH later – at some point of the project the spec changes – business analyst realizes that mistakes were made, process changes, the other department needs some of your functionality or another line of business has to be handled. There is no time compression or shortcuts available there – commands need to be amended and re-coded, views redesigned, events integrated with a different workflow. You are now thinking to yourself, “Why, oh why, did not I go with an application framework instead of the architectural one? rdquo;

The application framework goal is a way to get you through the “implementation ” part faster while giving you maximum flexibility on design and functionality part. If you do not have 80% of application built in 20% of the time, you will be late with the last 20%.

Flex itself is more of an application framework. It is not a library of patterns but rather a set of objects that are built to communicate and react. Flex uses code generators and other behind-the-scene techniques to achieve that. The key here is automation of implementation tasks by minimizing the amount of code while behaving predictably. That is done by explicitly checking the “related ” objects for specific interfaces. By not adhering to the implementation of these interfaces, the external frameworks require serious application development effort to support them.

MVC principals are also questionable in the Web2.0 world. The concept of fine granularity and validation on the client has serious security implications. You go to any AJAX show and you see one or two sessions with security specialists, cracking AJAX sites, getting free airline tickets, buying things for one penny, etc. It seems that every serious organization should be more interested in distributed model rather then pure client side solution. In that case most of the benefits of global MVC go out of the window.

Yakov. So far we have just a couple of the third-party Flex frameworks, but creation of the new ones is a viral thing, and the last thing I want to see in Flex community is more than a hundred of frameworks that do the same thing. We already see it in the Ajax world.

It “s not easy to quarrel when both parties share the same views. We really need other people “s opinions to better represent Flex developers who may see benefits of using frameworks.

This is A-m-e-r-i-c-a!

Some countries hate America, others want to be like America. I “ll just mention three episodes I “ve been personally involved in during the past two weeks, to tell you why I like living in America. Try to apply these cases to your country, and honestly answer to yourself, if the outcome would be the same. The names of the businesses and the money involved are real.

Case #1. I had to take my car for a scheduled service to the dealership called Ray Catena. Over the past 10 years, I “ve been leasing several cars from them. In the morning, I dropped the car there and had a short conversation with the person who was taking care of the paperwork and the loaner car.

I “ve asked, “How much this service would cost me? rdquo;

He said, “From $325 to $425. The car is pretty new, but you have high mileage, so it depends if we “ll need to replace the brake fluid in the system. rdquo;

When I picked the car in the evening, they “ve charged me $325. Apparently, they did not need to replace the brake fluid. What stopped them from charging me $425? I would not knew if they did or did no flush the brake fluid. They just did not. How much would you pay in the same situation in your country?

Case #2. Last year we switched our TV cable provider to Cablevision. Recently, we found out that the jack in the guest room did not have a signal. We called them, and they said, “We can send you a technician, and it “ll cost you $46 rdquo;. We made an appointment; the cable guy came in and fixed it for free. He said, “I thought, I “d need to do add an extra cable, but the cable was already there. Most likely, the technician who was doing the job last year just forgot to connect it rdquo;. If he “d send give me the $46 bill, I “d pay without saying a word. But he did not do it. How about the same situation in your country?

Case #3. My brother is visiting, and he asked me to help him with purchasing a laptop. We came to the electronic store from a chain called Circuit City, and found a laptop we liked. It was on display for $619. We “ve asked the clerk, “Please check if you have this model in stock rdquo;. He checked on the computer and said, “Sorry we are out of it rdquo;.

“Can you check the other stores in the area? rdquo;

He did, and none of the stores had this model.

“Can we purchase this one that you have on display rdquo;

“Sorry, you can “t rdquo;

Over the years, I “ve learned that one should never take the first “No rdquo; for an answer. I asked for the supervisor, and he saw that we were eager to buy this laptop, agreed to check if it had all required accessories. He found the bag with the battery, CD and the manuals, and said, rdquo;OK, we “ve got everything, and will be able to sell it to you as an open box deal for $549 rdquo;.

We “d be happy to get it even for $619, but he gave us a discount, because this laptop was already “in use rdquo;. How this story would end in your country?

America is not an ideal country, it has lots of crooks and businesses that are trying to get your money for nothing, but in general, the way of doing business here is healthy. Yes, there are stupid clerks that just do not care, and you need to take an extra step to get what you want, but the majority of people are running business honestly. These are some of the reasons why I really like living in America. All these little episodes are things that make the quality of life here a lot better.

Recently, I had a conversation with a fellow colleague, a software developer who was originally from India. I asked him how much money he would “ve earned if he “d return back to India with his current skills and industry experience? He said, “about $5K USD a month “, which is A LOT of money for people living there. But when I asked him if he had any plans to go back to India, he simply said, “No. The quality of life is a lot higher here rdquo;. I know exactly what he means.

Announcing a series of Weekend with Flex Experts seminars

Last weekend our company have conducted a two-day public training on Adobe Flex in Edison, New Jersey. The room was packed and we “ve received a really nice feedback from many attendees. Inspired by a success of this training, we “ve decided to repeat it in several cities across the USA.

This is how it works: we inject a solution of basic Adobe Flex techniques, design patterns, custom components and examples from the real-world projects. The procedure lasts 2×7 hours, the price of this weekend injection is $399 USD, which is cheaper than Botox and effect stays longer. You do not have to take the time off at your current project, and will have a chance to immerse into this hot technology on the go.

We are planning to run one such event a month and these are the first cities on our list are: Boston, San Francisco, Chicago and Philly. If you believe that there might be an interest to such event in other cities, we “ll gladly consider your suggestions.

Hey, captain, youll never be promoted to Major!

There was a great poet and singer in Russia – Vladimir Vysotsky. One of his songs is about his conversation with some Captain. They “d talk and drink, and at the at the end of the conversation, he said, “You know, Captain, you “ll never be promoted to Major rdquo;. I “ve been teaching programming to hundreds of people, and usually after the first couple of hours into the class, I can see if the student will make it or not. There was this guy who really needed a job. After attending one of my motivational talks he became convinced that Adobe Flex is the hot software and it makes sense to get trained and hit the job market early, when you can get a job if you know how to spell Flex. Then he sent me several emails asking what would be his chances of finding a job after attending my class. I never promise easy employment to anyone, especially in the USA . The market can be great, your technical skills are hot, and then you go to job interviews and you keep failing them. Why? What did you say there? Was it a wrong question that you “ve asked? A bad breath? What? You just do not get an offer. So I said, “I have no idea if you “ll be able to find a job after this training rdquo;. Anyway, he “s enrolled into the class. When other people were working on the labs and exercises, he “s chatting online. One day he left two hours early. He seemed like a smart guy, but he was on his own schedule. Needless to say that he did not do even a half of the hands on work. After the class, he sent me a thank you email, adding that now the only thing that “s left is finding a job. And I said to myself, “No Captain, you “ll never become Major! rdquo; Just being smart does not cut it. A guy comes to a rabbi asking him to talk to God so he could win in a lottery – lots of kids, no job, nothing to eat and the wife is pregnant again. The rabbi promised to talk to God. In a month, the man comes back asking, “Rabbi, did you talk to God about me winning the lottery? I still did not win! rdquo; The rabbi said, “Yes, I did, but have you purchase a lottery ticket yet? ” “No Captain, you “ll never become Major! rdquo;