Tag Archives: flex

Load and stress testing my website

Purpose of Load and Stress testing

The key goals of load testing are:

  1. Find out whether your website can support the expected # of concurrent users.
  2. At what load does the app break?

To do that, you normally follow these steps:

  1. Identifying the primary user path
  2. Identifying the expected # of concurrent users. (Both now and future)
  3. Set up virtual users to hit the app (load generation capability is the key factor to pick the right tool. You don't want too much hardware investment to generate the load you want, right? :wink:)
  4. Run the test
  5. Analyze the result (throughput under load, avg response time under load)

 

Challenges to load test Flex app

We have a web application that has Flex frontend talks to J2EE web application backend via AMF. How do we load and stress test this system? We certainly can just perform load test against our backend. However, it may need to expose our service via Servlet and load test it as typical restful web service. If we want to simulate Flex and load test through AMF. We need to find a way to capture the AMF requests from Flex client and replay it in our load testing suite. To do that, we can use Charles http proxy to capture the AMF request and tell JMeter to load test our application via replaying this AMF request. This  article can give us the detail. However, Charles is a commerical product. If you want a free solution, you can try this.

I know that JMeter comes with proxy to record the request. You can try it out to see whether you can exam the AMF message. Let me know if it works!

JMeter

Load is all of the users using your web site at a point in time. Load includes users making requests to your web site as well as those reading pages from previous requests. However, we do need some way of differentiating between all clients and those clients actually making requests to our web site. We use the terms concurrent load and active load (making request) to make this distinction. We use the JMeter to help us to generate the load to our system. In term of load generation, we should make sure that we can simulate the peak load. JMeter is a great load testing tool. I have heard that Google is using this to load and stress test its application.

To use JMeter, follow the steps below:

  1. Set up Thread Group – use to model concurrent virtual users and decide how you want the load be generated.
    • Number of threads.
    • The ramp-up period (it tells JMeter the amount of time for creating the total number of threads). At the beginning of a load test, if the ramp-up period is zero, JMeter will create all the threads at once and send out requests immediately, thus potentially saturating the server and, more importantly, deceivingly increasing the load. That is, the server could become overloaded, not because the average hit rate is high, but because you send all the threads' first requests simultaneously, causing an unusual initial peak hit rate. The rule of thumb for determining a reasonable ramp-up period is to keep the initial hit rate close to the average hit rate.
    • The number of times to execute the test.
    • If the client machine running JMeter lacks enough computing power to model a heavy load, JMeter's distributive testing feature allows you to control multiple remote JMeter engines from a single JMeter console.
  2. Introduce user think time
  3. Specify response-time requirements and validate test results.

To get familiar with it, here are some articles I found it useful

  1. Stress testing with JMeter by Daniel Rubio – Linux.com
  2. Loading testing with Apache JMeter by Kulvir Singh Bhogal, – Devx.com
  3. JMeter distributed testing
  4. JMeter recording testing
  5. Load test your drupal app scalability with JMeter – Part 1, Part 2
  6. Load testing with JMeter – powerpoint – very good!
  7. Scalability Factors of JMeter in Performance Testing – response size, response time, protocol, hardware configuration, load generating tool architecture and configuration, complexity of client-side processing.
  8. JMeter Tips – Javaworld

 Reference

  1. Someone has written a nice article in sys-con to talk about how to load test Flex application.
  2. Use FlexUnit for stress testing
  3. Test Remote Data Service via FlexUnit
  4. Load testing with log replay – interesting idea
Leave a comment Continue Reading →

Streaming data to your grid

Push data to client

Traditional web application is based on request and response model that information is delivered as a single payload and then immediately close the connection to the client. To keep the client in sync, we normally pull the server periodically. This approach may generate unacceptable load to the server. To solve this problem, we want to have a push mechanism from server to client. This is why Comet is defined. Comet is a generic term describing various approaches to send data asynchronously from a Web server to a client without the need for the client to explicitly request the data. It is an essential technique for any real-time event-driven web applications, where the majority of events occur on the server and data must be “pushed” frequently to the client. To achieve this, Comet servers must maintain a continuous connection to each client for the duration of the session.

 

OK. How to maintain a continuous connection to each client for the duration of the session?

If you try to adapt traditional server to the Comet methodology, it may not scale and often fails after a few thousand simultaneously open connections. A true Comet implementation requires a very different kind of server architecture to be efficient and scalable – Liberator (a solid Comet server that are used by the financial industries. However, it is written in C and not open source although it has FREE edition distributed).

To understand this statement a little bit more, we need to know how traditional web containers handle the request. They are under one request per thread model.

  1. The client , typically , a browser sends request for resource to a web server.
  2. The server has a listening thread that keeps track of incoming connections.
  3. When a request arrives , the server uses one process or thread to process the request.
  4. The resource is returned to the client and the connection is closed.

In this model, the number of requests that can be served in a second would depend on two things

  1. How many threads are there to handle the client requests
  2. How long it takes to serve one request.

If all threads of server are busy, then the incoming requests are put in a queue. The server would return to the requests in queue when server threads become free. The number of requests handled per second is always greater than the number of allowed simultaneous connections. All this is made possible because the time required to process a request is very short. In other words you can server more requests in a second than you have threads.

However, there are one breed of applications that need to hold onto the connections. Think of applications that require real time data coming to clients (stock tickers)  or think of applications where low-latency is required. In the above traditional web model, the browser has to re-connect to get the new data. (Polling). If the new updates “can”  happen with high frequency (e.g. a chat application) then the polling frequency also has to increase .  An alternative to high frequency polling is to use push based applications. For push based application, once the browser connects to server, the server will maintain the connection till the browser time-out (server response stream is not closed) and keeps flushing data down the connection as and when they become available. In servlet container, to hold the connection, your thread in the service method cannot exit the method. Otherwise, the response stream will be closed. So what you do is, you block the thread on some condition within the service method. So the thread will block for your condition. When push data becomes available , this thread writes to response stream and again enters a blocked state. So as long as you hold onto the connection, you can not return this thread to the thread pool. And as more and more “push” connections are established you would run out of threads! To remedy the problem, the possible solutions are:

  1. Increase # of server threads.

Flex Push

There is confusion that whether BlazeDS supports real time messaging. Yes it does :wink:. In fact, BlazeDS has a full spectrum of channel types ranging from simple polling, to near-real-time polling, to real-time streaming.

  1. Simple polling – ping the server from Flex client using the traditional request and response model
  2. Near-real-time polling (long polling) – Instead of acknowledging right away, the server could hold the polling request until there’s a message for the client. This ensure the messages are delivered to the client as soon as they become available. The caveat for using long-polling is the thread limitation in most application servers. At this moment, BlazeDS could not support more than a few hundred long-polling clients on most application servers. However, this problem could be resolved once servers like Tomcat start to support asynchronos, non-blocking connection threads. Update: Now Tomcat 6 supports NIO.
  3. Real-time streaming – BlazeDS supports real-time message streaming over AMF and HTTP. Unlike long polling, which closes and reopens the connection upon receiving a message, streaming keep the connection open at all times. Streaming suffers from the same thread blocking issue as long polling. A cap must be set so the server is not hang by idle threads.

The reason why people are confused is that Adobe doesn’t release its proprietary push solution RTMP to BlazeDS. So, RTMP isn’t available as a channel in the BlazeDS configuration files. BlazeDS lives in a Servlet container and hence constrained by one-thread-per-connection limit whereas LCDS has NIO-based channels that can scale up to 1000s of requests. On the other hand, BlazeDS has the advantage that it’ll work over port 80/443, whereas LCDS will use some port for persistent connections that would require a firewall configuration. Once the servlet that implements BlazeDS is revved to support Comet Events under Tomcat 6, and then Jetty Continuations, then the long polling technique will be fine.

UPDATE: We are waiting for a solution that supports Comet Events under Tomcat 6. Then BlazeDS can be coupled to the Tomcat NIO HTTP listener and be able to scale as well as any NIO based server software.

I have learnt from this article that you can create a channel set in client side. So Flex can fail-over to other channels until it gets connected or the list is exhausted.

Marc has put an effort to build a better data grid like a spreadsheet in Flex. (check this out)

Reference

Here are the references I used for this article

  1. Tuning Apache and Tomcat for Web 2.0 comet application
  2. Performance of Grids for Streaming DataThis shows you the performance numbers on various frontend technologies. Again, Flex shows us a good result.
  3. Are raining comets and threads? – Comet Daily
  4. Comet & Java: Threaded Vs Nonblocking IO
  5. JDK 1.6 uses epoll to implement NIO
  6. BlazeDS dev guide
  7. Achieve performance breakthrough using BlazeDSFarata System put an effort to write its NIO channel that runs on Jetty 7 and receive promising result.

 

Leave a comment Continue Reading →

Flex Annotated Charting

Recently, I want to extend the LineChart in Flex. I want to have line chart with event annotated like Google Finance.

 
First of all, I googled the Net to see whether anyone had already done it. It was even better if I could find any open source project related to this. Below are the interesting things I found:
  1. Dow Jone Interactive Chart (commerical – it is exactly what I am looking for)
  2. Interactive Bubble Chart (open – although it is not exactly want I want, but if I believe the code can benefit me if I need to customize line chart. :cool: I may just need to draw the interactive small bubble on the line to get my job done!)
  3. This demo gives you tons of chart samples. They are all great example although none of them satisfy my current need.
  4. This demo is close to what I want. From this demo, I notice I can use “annotationElement” to draw on top of the data series. However, the trick is to convert the data points to pixel coordinate in order for me to draw something that can move along with the graph even someone stretches it. To make thing easier, Ely Greenfield has created DataDrawingCanvas that helps us draw on the chart with only data points specified instead of pixel coordinates. This class extends the ChartElement like AnnotationElement does (blog). That is amazing!! Thanks!!! :smile:
  5. Google Finance Chart (It is exactly what I want. I wonder I can get the source of it)
    • I have found the blog and powerpoint of this sample (1/7/2009)
    • Google uses the Flash/ JavaScript integrate kit to get it works (blog) – I heard that it is very nice combination of Flash and AJAX. This is similar to MeasureMap‘s use of the kit.
    • It is open source example!!! (code). Thanks for Brendan Meutzner!!
    • Brendan also shows us how he created his demo in 5 steps to help us understand how to build it ourselves.
    • Step 1, Step 2, Step 3, Step 4, Step 5 – enjoy!!

Reference

Useful resources:

  1. Data Visualization by Tom Gonzalez. (Tom created an open source visualization framework named Axiis. It looks great. Once I get a chance, I will dig into it) – 7/31/2009
  2. Building a Flex Component by Ely GreenField
  3. Create component and enforce separation of concern
  4. http://www.edwardtufte.com/tufte/ (Edward Tufte – famous guy in data visualization)
  5. http://www.insideria.com/2008/03/image-manipulation-in-flex.html (Image Manipulation)

 

Leave a comment Continue Reading →

Wiring up Flex, Mate, BlazeDS, Spring, Hibernate and MySQL with Maven 2 – Part 1

Introduction

This article is written on top of the great work that Sébastien Arbogast has done. He has written 3 articles that showed you how to wire up Flex, BlazeDS, Spring, Hibernate and MySQL with Maven as build process. I have included his articles below as your reference.

  1. The Flex, Spring, and BlazeDS full stack – Part 1: Creating a Flex module
  2. The Flex, Spring and BlazeDS full stack – Part 2: Writing the to-do list server
  3. The Flex, Spring and BlazeDS full stack – Part 3: Putting the application together

I have found Sebastien’s work as a good foundation for my own project. To contribute back to the community, I will write a series of articles to show you how can customize and extend the todolist sample.

What is in the Part 1 of the series…

  1. Enhancements on the Maven build process
    • Leverage RSL to factor our the framework swc, so the size of the application swf will be reduced. Apart from that, I also take advantage of Flash Player Cache that is available after version 9 update 3 to cache the framework libraries.
    • Clean up the Flex and BlazeDS dependencies in POM as the latest version of the sdk is available and the BlazeDS dependencies are officially available.
    • Include some common reports for maven site generation
    • Embed Jetty web server in the build process for quick deployment and testing
  2. Document how to get the sample up on Eclipse for development
  3. Use Mate as Flex framework
    • Restructure ToDoList sample to leverage Mate framework
    • Factor out Mate as RSL and integrate it with Maven build process via Flex-mojo plugin.

What are in the coming articles…

  1. In part 2 of this series, I will show you how to use flex-mojo to build a modular Flex application.
  2. In part 3 of this series, I will show you how to test your flex app via FlexUnit (Unit test) and FlexMonkey (Functional test)
  3. In part 4 or this series, I will work on server side. I am planning to add monitoring, caching and security to the server side.

Review “ToDoList” sample

Before I start my journey, let me highlight what Sebastien has done first:

  1. Sebastien’s sample demonstrates how to use Maven as a build process. There are 3 parts or subprojects in his sample. They are:
    • todolist-config (configuration files shared by other subprojects)
    • todolist-ria (Flex frontend)
    • todolist-web (Server side that supports the Frontend)
  2. All these subprojects are considered as modules of the main project (root POM). Finally, they are combined together into war artifact and ready to deploy to Tomcat or other J2EE webapp server.
  3. Flex frontend and backend communicate through a binary RPC protocol – AMF. AMF is considered to be the simplest and fastest remoting approach available in Flex. Recently, Adobe has released BlazeDS as an open source implementation of AMF spec. In this sample, BlazeDS is used. To use BlazeDS, there are few things you need to do:
    • Externalize your POJO service via BlazeDS. This sample shows you how to integrate BlazeDS with Spring
    • Make BlazeDS endpoints availabe to the Net via Servlet.
    • Have frontend and backend shared the same BlazeDS configuration files.
  4. In this sample, you can also find out how to use flex-mojo maven plugin to compile the Flex frontend code into swf. Apart from flex-mojo plugin, there are other two good plugins worth to mention:
    • maven-assembly-plugin - can be used to bundle all the files under a directory into a zip file. It is used by todolist-config to bundle all the configuration files (service-config.xml and remoting-config.xml) into a zip during the package phase.
    • maven-dependency-plugincan be used to unpack the zip file and move to the place you want. It is used by todolist-web to unpack the config zip during the generate-resources phase.

Enhancements on maven POM

I have modified the sample’s maven pom as follows:

  • Link to new repository “Sonatype Forge” in the root POM. So, I can use the new version of flex-mojo and simplify the todolist-ria adobe framework dependencies. Apart from that, I also take away the private repository from Sebastein because BlazeDS libraries are available in official maven repository (Note: The BlazeDS libraries available in official maven repo are in version 3.0 instead of 3.0.0.544. So, you need to modify the webapp pom correspondingly).

    <repositories>
        <repository>
            <id>flex-mojos-repository</id>
            <url>http://svn.sonatype.org/flexmojos/repository/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>flex-mojos-repository</id>
            <url>http://svn.sonatype.org/flexmojos/repository/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

  • Because I link to Sonatype repository, I can have my todolist-ria depends on one flex-framework pom dependency instead of all the swc dependencies. Note that the pom dependency is a way to factor out all the adobe swc dependencies that makes your pom easier to maintain.

        <dependency>
            <groupId>com.adobe.flex.framework</groupId>
            <artifactId>flex-framework</artifactId>
            <version>3.1.0.2710</version>
            <type>pom</type>
        </dependency>

  • I include mysql driver as dependency in my webapp pom. I think it is cleaner to bundle it in war. I have also added jetty plugin in the POM so you have a web server embedded in the build process. With this, you can run this sample application right after you check it out from svn (assume you have maven 2 installed). To start jetty, you can issue the following maven command under your webapp project.

project_root> mvn clean install
project_root/jp-web> mvn jetty:run-war

  • I have included some reports that will be shown after site generation. You may not be able to do mvn site-deploy because it is linked to my web hosting site. However, you can modify it for your own sake.

Get the sample up on Eclipse

To develop on Eclipse, you can follow the steps below:

  1. Create Eclipse project file via running the command below at the project root. This will create 2 eclipse projects. One for todolist-ria and one for the webapp. You noticed that I use the -Declipse.downloadSource=true to include the source files of my dependencies in my eclipse project. Therefore, I can get to the source code if needed.

mvn -Declipse.downloadSource=true eclipse:eclipse

  1. Import the projects into Eclipse
  2. Add new variable M2_REPO and set it equals to [home]/.m2/repository
  3. If you have installed Flex Builder plugin to your Eclipse, you can Add Flex Project Nature to the todolist-ria project.
    • Select Application Server Type: J2EE
    • Put check on “Use remote object access service” with LiveCycle Data Service selected.
    • Set up the path. I have my tomcat installed under C:\tools with default 8080 as port. You should make the changes if you installed it differently.
    • Remove the generated main.mxml under the src folder.
    • Set index.mxml under src folder as default Flex application file to run.
    • Use Default Flex SDK in Flex Compiler Configuration instead of Server Flex SDK
    • Right click and select Recreate HTML Template if you see error.
    • After all these, you have configured your Flex application pointing to the webapp server and sharing the BlazeDS configuration files. You can verify in Flex Compiler Configuration’s Additional Compiler Parameters. See whether you see this: -services “C:\tools\tomcat-6.0.16\webapps\jp\WEB-INF\flex\services-config.xml” -locale en_US
    • Move the war to your tomcat’s webapp folder and start it under remote debugging setting. If you are using window, set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8787,suspend=n under your bin/catalina.bat.
    • Start your webapp via bin/startup.bat
    • Put breakpoint under TodoServiceImpl save method and start remote debugger on localhost:8787
    • Right click the index.mxml and Run As Flex Application.
    • Add a new entry and save it on the flex app. :razz: You should see your remote debugger halt at the breakpoint for you to debug.
    • Now you can change your flex code and test it out without leaving your Eclipse. However, if you modify the service in webapp, you need to run “mvn clean install” and deploy the war to the tomcat before your flex code can call your server-side code via AMF.

Use Mate as Framework

If you are not familiar with Mate, click the image below that moves you to a nice presentation.

 

What did I do to restructure the todolist sample to make it Mate app?

  1.  

Download

I have made my work available at: www.solutionhacker.com/wp-content/uploads/todolist-jp-modified.zip

Reference

Below are the references I used for the article:

  1. Flex mojo compiler user guide
  2. Flex mojo dependency scope rules
  3. Flex 3 feature introduction: Flex 3 RSL
  4. Improving Flex application performance using Flash Player Cache
  5. FNA archetype projects 

 

Leave a comment Continue Reading →

Why Flex for RIA, no AJAX?

Here is the list of reasons why I chose Flex for the RIA development.

  1. Write Once Deploy Everywhere – Flex generates SWF that runs on top of Flash Player VM and behaves consistently across different browsers, even mobile phones later. With this, all the browser compatibility issues are basically offloaded by Adobe.
  2. Solid programming model with rich widgets and libraries.
  3. AMF makes Flex object to Java POJO communication possible. No need to use verbose XML – Check out BlazeDS.
  4. Flex IDE is a plugin in Eclipse that gives stepwise debugging, UI design console, code completion and more. Working with Actionscript is like Java.
  5. Flex SDK is open source and free.
  6. Great support on video streaming
  7. Integrate with HTML, Javascript and CSS, so it is not invasive adoption.
  8. Support offline application via AIR – Adobe has been working on the Adobe Integrated Runtime (AIR) that allows for using existing web application development skills to build and deploy desktop applications. AIR is still in early development, but promises to allow developers to use their newly learned Flex skills to build desktop applications. No need to learn Swing, Applet…etc.
  9. Provide several RPC methods like HTTPService, WebService, AMF and JSON. AMF is 10x faster than SOAP. James Ward developed his Census Flex application to provide performance benchmarks for the different RPC methods in the mainstream RIA technologies. (Download)
  10. You can keep the state in the Flex app and have your server completely stateless.
  11. More to come! :)

 

Leave a comment Continue Reading →

Flex – Cairngorm Microarchitecture

What is Cairngorm?

Adobe Consulting Group has defined an architectural framework for Flex application, named "Cairngorm". The framework has borrowed quite a bit of design patterns from GOF and J2EE. Its goal is to help us to layout the groundwork for complicated RIA. It is interesting to see how those patterns work together in a seamless way. The framework not only cleans up our code, but it also decouples our components. The result is very neat and elegant!

flexarch.JPG

Lets go through some interesting points for this microarchitecture. I assume you already read this excellent 6 parts articles from Steven Webster.

Encapsulate your Flex component and make it no dependency to the Cairngorm framework to promote high reusability

  • To do a better encapsulation – input (VO) and output (event) are non-Cairngorm object.
  • Component internally use VO to bind to its controls and external link VO from ModelLocator to it. So, whenever the VO in ModelLocator be changed by Command, the components’ controls that link to it will be updated.
  • User gesture is first captured by the component via event listener and then re-dispatched as custom event and bubbled up. Have the View that uses the component to capture the custom event and re-dispatch again as one type of CairngormEvent with VO loaded. In Cairngorm 2.2, you simple can call the "dispatch()" method from the CairngormEvent. Then, the FrontController can take care the rest. The CairngormEvent dispatched should be non-bubbled and cancellable.

View is the place for layout the controls and interact with Cairgnorm objects (normally it is non-reusable)

  • View can set up control with VO from ModelLocator and capture custom event from control and re-dispatch it as a type of CairngormEvent.
  • View contains state definition that is explicitly binding to the ModelLocator where it contains what state the View should be. The code below indicates that when the search_state is changed, the searchState() method will be invoked and alter the state of the View.

[code]]czoxMTc6XCImbHQ7bXg6QmluZGluZyBzb3VyY2U9JnF1b3Q7e01vZGVsTG9jYXRvci5nZXRJbnN0YW5jZSgpLnNlYXJjaF9zdGF0ZX17WyYqJl19JnF1b3Q7IGRlc3RpbmF0aW9uPSZxdW90O3NlYXJjaFN0YXRlJnF1b3Q7IC8mZ3Q7XCI7e1smKiZdfQ==[[/code]

Command should be the one that changes the model

  • FrontController is a registry that associates Event with Command. This mapping can be M:1.
  • Consider ModelLocator is a mediator for Views to interact one another via changing the model.
  • Delegate may intercept the response via registered its result and fault handler. The goal is to hide the detail from remote call. Therefore, it is good practice to convert XML to VO (via Factory) before invoking Command’s result and fault handler.

[code]]czoxOTU6XCI8Zm9udCBzaXplPVwiMlwiPnZhciB0b2tlbjpBc3luY1Rva2VuID0gc2VydmljZS5zZW5kKHBhcmFtcyk7IHZhciByZXNwb3tbJiomXX1uZGVyOm14LnJwYy5SZXNwb25kZXIgPSBuZXcgbXgucnBjLlJlc3BvbmRlcihzZWFyY2hCb29rc19vblJlc3VsdCwgc2VhcmNoQm9ve1smKiZdfWtzX29uRmF1bHQpOyB0b2tlbi5hZGRSZXNwb25kZXIocmVzcG9uZGVyKTs8L2ZvbnQ+XCI7e1smKiZdfQ==[[/code]

How to unit test Cairgnorm-enabled project

  • VO, Service, FrontController, Event and ModelLocator are simple classes that are not subject to test.
  • Command can be tested with Mock Delegate
  • Model can be tested if it contains logic
  • Factory can be tested if it contains parsing logic.
  • Delegate can be tested with Mock Service (but a bit tricky as how to write a mock service)
  • Control can be tested via addListener for the custom event thrown.

References

Update

Recently, I have heard that PureMVC provides a clean framework than cairngorm as cairgnorm uses a lot of singleton framework class. I haven’t got a chance to look into it. Be sure will keep you update if I find it interesting.

 

Leave a comment Continue Reading →

Flex Architecture – MVCS

I have come across an excellent article from Joe Berkovitz that talks about a “right” way to architect your application. I like this article a lot. It gives me a good refresh of what I have learnt in these years. I decide to spend a little time to go over some of the key points from this article.

Isolation and encapsulation are the keys. Isolating concerns opens the door to accommodating change, because it puts boundaries on the ripple effects of changes within the code. Isolation makes modular development and testing easy. Isolation makes it easy to have different people work on different pieces. Finally, isolation makes it easier to envision ways of improving the user experience that are generalized and powerful.

The first rule I learnt in component design is “Reduce coupling and increase cohesion”. The goal of this is to reduce the amount of interactions among components and in turn promote reusability and reduce complexity. This concept proven to be useful in my career life. The tricky part of it is to draw a line around a component and provide a clear responsibilities (ie. via interface) and interactions of it (ie. communication). A good architect can make it very clean and simple whereas a novice designer cannot make a component reusable without associated with different dependencies. In this article, the author focuses on the design in UI, but the rules apply to all aspects of design. A term “MVCS” is mentioned that adds “Services” to the common known MVC pattern. Service is responsible to encapsulate the communication with the external world. Here is the diagram of the MVCS:

MVCS

In MVCS, Model captures the state of the application. It doesn’t know any of the non-Model classes and it carries no intelligence (ie. no function but read/write for properties). According to the author:

In general, avoid functions, since they introduce more complexity, and stray interactions with non-Model objects can creep in. Complex logic for model objects usually belongs in the Controller.

However, from what I have learnt, there are certainly logics belongs to the model classes. A domain model without any behavior is termed as “Anemic Domain Model” by Martin Fowler. “…this is an anti-pattern because it’s so contrary to the basic idea of object-oriented design; which is to combine data and process together.” When I look closer, this is the model that supports the UI but not the domain model in the server side. Is the same rule applied in this area as well? On the other hand, how the model notifies the View if its state is changed? In Flex, you can define your properties as “Bindable”. Whenever the state of the model is change, an event will be fired to notify the associated View.

View references objects in Model via data binding. Bindings are used to move data from sources that change into destinations that need to be change-aware. Besides,View captures users interaction (via event handler registration) and hands off action to Controller (via calling Controller’s function in event handler). Controller, like Session, is application-wide object that should be obtained through a static instance variable to avoid having to pass all such objects all over the application.

Controller is the center of the application. It is the place where application logic and behavior are implemented. It is the only part of the architecture that communicates with all the other parts, thus relieving the View, Model, and Service packages from needing to know too much about each other.

Service objects make up a layer of objects that handle all communication with the outside world like Web Service and Http calls. Besides, Services act as factories for Operation objects; it is actually these Operations that do the work of communication by initiating requests, handling responses, and dispatching status and completion events. Why not just do it internally rather than generate the Operation for controller to call? According to the author, it gives more flexibility. However, I don’t see such much usage of this flexibility. So, I still prefer doing simple Service’s method call… :)

 

fig_09.gif

Leave a comment Continue Reading →