Hi, I'm Ben. This is my blog. I write about Flex,
Flash, software development, and other miscellany.

Swiz example application with Passive View pattern

Passive View is another presentation pattern that can be used to increase the testability of graphical applications. It does this primarily by extracting all logic and state from your views, making it pointless to test the view itself. In fact, in the article linked above, Martin Fowler says the following:

With the view reduced to a dumb slave of the controller, you run little risk by not testing the view.

You instead test the component to which the logic and state have been extracted. This component can be referred to by names such as mediator, presenter or controller but the name itself is irrelevant. What is important is that it is not a view component (meaning it does not exist on the display list, in Flash/Flex specific terms), which are inherently hard to unit test. In the example application I have created I refer to these components as mediators.

Example Application

For this post I have simply converted the Swiz example application I created using the Presentation Model pattern. The conversion took maybe 30 minutes, which includes looking up some of the specifics of the pattern, because I had not actually implemented it before.

Application :: Source

Motivations

One of Swiz’s biggest strengths is the flexibility it affords you when using it. Rather than enforcing (or even suggesting) a particular architecture, it provides tools and utilities that help you to create well architected applications. I think showing the same application built with different (albeit similar) presentation patterns demonstrates this point quite well. I will also admit that I was influenced by the RobotLegs Best Practices document in selecting Passive View as the pattern to demonstrate since they demonstrate/promote the pattern there. Hell, I will even admit there was a bit of “anything you can do, we can do better” sentiment on my part. :) That is not meant to take anything away from the RobotLegs team as they are certainly a smart bunch of guys, but I wouldn’t have joined the Swiz team if I didn’t think it was the best thing out there.

Thoughts on Passive View

I sort of like that your views become plain MXML with no logic, state or external references whatsoever when using the Passive View pattern. What I don’t like is what your mediator/presenter/controller becomes in order to purge your view of those things. I feel like you end up with a frankenstein class that is part (presentation) model, part controller and part code behind.

It is not truly code behind since it uses composition rather than inheritance, but it feels the same. You are reaching into the view to add listeners to its child components, setting properties directly on its child components, etc. Handling events from those child components is like a controller, but you also end up storing some state for the view as well. You could obviously break that out into a separate model class but for most views that is going to be massive overkill. I suppose that presentation models are or can be somewhat of a controller and model combination as well too though. I think adding all the knowledge of the view and its internals is what creeps me out most.

I also feel like Passive View fights against the platform a bit. Since the view has no references to anything, binding is not an option. The view can only be updated by user interaction or manually from the mediator, and even for the extremely simple example I created this felt very tedious. I also wonder if testing the mediator could not potentially be complicated by needing an instance of the view it mediates for operation. Flex Unit 4 likely overcomes much of what would have been painful in the past in this area, but I feel like removing view components from the testing process completely is ideal.

In summary, I think Passive View is a decent pattern, but I won’t be abandoning Presentation Model to use it. In my opinion the drawbacks outweigh the benefits, but the same may not hold true for your particular needs and/or preferences.

Further reading

Be sure to read the Martin Fowler piece linked at the beginning of this post (and anything else by Fowler you have time for), and for another example of the Passive View pattern in Flex check out Paul Williams’ post on the topic.

Enjoy!

Coding in Flex Builder, Compiling in Flex Builder: A Better Flash Workflow

A couple of weeks ago, I posted about a workflow I had devised that allowed me to utilize Flash library symbols but still write my code in Flex Builder. While Adobe apparently thinks this awkward hybrid approach qualifies as “integration”, I thankfully discovered a better process just a day or so after my posting. I discovered the main concept of this better workflow from Arpit Mathur’s blog.

What it basically boils down to is using Flash authoring to create a SWC that you then use as a library in your ActionScript project in Flex Builder. Getting Flash authoring to generate a SWC is as simple as checking a box in the Publish Settings dialog.

exportSWC

Then make your ActionScript project use the resulting SWC.

useSWC

What you can then do is create ActionScript classes that extend the symbols in your Flash file. As long as you give your symbol a linkage name it will be available for extension (and will itself extend MovieClip by default), allowing you to add behaviors and logic using class-based ActionScript like developers expect and prefer to do. The convention I have settled on is to add “_Symbol” to the end of the class names specified in Flash authoring to make it completely clear where everything originates.

myButtonLinkage

The other major advantage this approach has is that it renders the “Automatically declare stage instances” debate irrelevant. You can let the designers leave this setting off and write bits of timeline code if they need to and your classes that extend their symbols will still work. Regardless if they are specified manually in class files for the symbols themselves or Flash generates the classes automatically, the children of your symbols (text fields, child movie clips, etc.) will all be available to your code.

myButtonClass

With this simple structure of a symbol in Flash:

symbol

You can write a class like this to control it.

The result is a functioning button that allows the designer to use the expressive, proven tools in Flash authoring to create the graphical assets while allowing the developer to use the mature code editing environment of Flex Builder. This process has proven valuable and efficient over the last two weeks and it addresses the major shortcoming of my previous post. That was an inability to use a proper debugger, and it also lets the designer and developer work in parallel, both in the environment most familiar to them. It lets each tool and each team member do what they do best.

While I developed this workflow (not that its an original one by any means, just new to me) due to my assignment on a project that could not use Flex, I actually think it could be valuable in Flex projects as well. For views that are highly detailed and/or non-standard it may very well be easier to let your designer create them in Flash than it would be to create some crazy MXML file that carefully layers exported images and animations that you then try to wire up and orchestrate with code. Simply write a class that extends your designer’s symbol and manipulates it as needed.

To me this seems like the best kind of workflow available today by far, and so its really disappointing and frustrating to think Adobe may not be taking things a step further in their next releases. We don’t need or want Flash Builder to compile and run our projects in Flash authoring. What we need are workflows that allow us to use tools that do their job well and that we’re comfortable with, and that simplify the inevitable round tripping between design and development. Having Flash Builder trigger compiles in Flash authoring may sell more licenses to the uninformed, but its a sad excuse for integration from a company that creates tools ranging from authoring to runtime.

All code and sample files for this post can be found in my Google Code repository.

Flex Builder error: The project properties files could not be read.

I started receiving this error in a Flex library project tonight and did some Google-ing. Thanks to a comment by Eric Hélier on this bug I was able to quickly fix the issue.

Eric mentioned the marking of Flex SWCs as external, which I had recently done. In my case though, it seemed to be marking locale as external that messed things up. I deleted the following line from my .actionScriptProperties file and the error disappeared, and leaving the locale merged in does not seem to affect SWC size anyhow.

<libraryPathEntry kind="1" linkType="2" path="${PROJECT_FRAMEWORKS}/locale/{locale}"/>

I hope this helps somebody out of a jam, preferably late at night or right at crunch time. :)

Coding in Flex Builder, Compiling in Flash Authoring

Nostalgia and complaining

Years ago, before AS3 and Flex 2 were on the scene, I was a Flash developer. I dabbled in other things like PHP, JavaScript and the horrific “classic” ASP, but Flash development with AS2 was always more interesting to me. I worked with great designers who of course used Macs, while me and the rest of the developers were on PCs. (Don’t worry, I use a Mac now.) In order to preserve the designers’ fonts and hand crafted animations, we taught them how to assign linkage names to their symbols and would have them deliver a .swf to us that had nothing on the stage, allowing us to pull symbols out of the library as we needed. Using the fantastic MTASC compiler and an editor like PrimalScript, our class-based AS2 code would be injected into the designers’ .swf, bringing the site/game/whatever to life. Ahh, those were the days.

Fast forward to last week when I was assigned to my first ever non-Flex AS3 project and discovered that developing like we used to in Flash (tying AS classes to library symbols) is pretty painful these days. Or at least it was for me, until I constructed a very convenient workflow that you can probably guess at based on the title of this post. Now, I should probably explain what I mean by painful. You can write your AS3 classes in Flash authoring, and the process is very straightforward; just create classes whose names match the symbol linkage names and you’re done. Just like AS2. However, Flash authoring’s code editor is absolutely abysmal. I mean, I knew it was bad, but I was actually shocked at how bad it is. It won’t even create import statements for you when you create properties! If you have used Flex Builder or any other decent editor for more than 10 minutes, this is completely unacceptable. You could also write your code in Flex Builder, save, switch to Flash authoring and then test movie or publish from there. Honestly though, do you really want to do that 500 times a day? Me neither.

So, what is this better way you ask? Well, we use one improvement that did come with Flash authoring’s support of AS3, which is the document class construct. This means that you simply create a custom class to represent your application, make sure it extends MovieClip, and tell the .fla to use it. We don’t need any code at all in our .fla, unlike back in the day. This essentially means that your custom class is your root timeline, and adding display objects to it is like adding them to the stage.

Coding in Flex Builder

Since I use a Mac, Flex Builder and FDT are the only realistic options for AS3 editors, as far as I know. If you are on a PC, FlashDevelop is also a great program. Now, Flex Builder allows you to create ActionScript projects. In contrast to a Flex project, I assumed an ActionScript would be devoid of any reference to Flex SDKs, but this is not the case. Your ActionScript project will still reference an SDK in the compiler settings and in the build path dialog, but that is OK. Since you don’t reference any Flex classes, you will not be pulling the framework into your .swf. I think it is only referenced so Flex Builder knows where to find mxmlc, but I am not completely sure. In order to use library symbols as class instances, you will need to create corresponding classes (that extend MovieClip) for them that match the name specified in the their linkage field. Whether you need to add custom code or not, the classes must exist in order for you to reference them in Flex Builder. To reference their properties, like child text fields or buttons I declare those properties in the class and turn off “Automatically declare stage instances” in the .fla’s publish settings.

Compiling in Flash authoring

OK, none of that was revolutionary but now comes the hard part. How do you compile/test your project without having to switch back to Flash every time? The first piece of the puzzle is to use the flashcommand Python script that Mike Chambers posted a long time ago. (It is only for OS X in its current state but I would assume creating a PC-friendly version wouldn’t be too hard.) All this really does is open Flash if necessary, and compile the .fla(s) you tell it to, by writing JSFL to a temporary file and then running a line of AppleScript to execute the JSFL code. That is really great, but switching to Terminal every time I want to compile is no better than switching to Flash. I needed something I could trigger from within Flex Builder, so I naturally turned to Ant. All you need is a super simple build file, like this:

As you can see, it just sets up a couple of properties and asks Python to run the flashcommand script. The -e argument tells flashcommand to include doc.exportSWF() in the generated JSFL, which will publish the .swf to the location specified in the -o argument. If this is all you need to do, but want to then launch the newly created file in Flash Player, you can add the following to your build.xml file.

That was my initial approach but it makes viewing your traces kind of a pain. The easiest way I found was to tail your flashlog.txt file but that still kind of sucks. Its especially bad because a LOT of .swfs on the web still include trace statements, meaning your Terminal is flooded with statements generated by every banner ad running in your open browsers.

What I ended up doing was to edit flashcommand so that the -e argument also adds fl.getDocumentDOM().testMovie() to the generated JSFL, causing Flash authoring to execute a test movie action. I also added activate to the end of the generated AppleScript so that Flash’s test movie window would be brought into focus and ready for interaction. This allows you to use Flash’s built in Output panel to view your trace statements, and your trace statements only. (I tried making the test movie option a separate command line argument but couldn’t get it working correctly. If any Python hackers out there want to show me the way I’d be much obliged.)

Set up a keyboard shortcut in Flex Builder for running Ant and your workflow is almost identical to a Flex or code-only ActionScript project. Your .swf will be generated and published to whatever location you’ve specified, and will also be opened in Flash authoring for visual inspection and testing. I am probably not the first to come up with something like this, but I didn’t find any good links on the subject and other people expressed an interest in hearing about my workflow. If you have suggestions on further improvements (like how to use Flex Builder’s debugger for these projects) I would love to hear them. Regardless, I hope this is useful to other coders who find themselves needing to develop AS3 projects that associate custom classes with library symbols.

If you’d like to replicate this setup, you can download my modified version of flashcommand.

Enjoy!

Switching domains

If you subscribe to the RSS feed it should hopefully be seamless (don’t fail me now Feedburner), but I thought I should mention it here just in case. This blog is moving to benclinkinbeard.com, and returnundefined.com will be forwarded to the new domain. Please let me know at ben.clinkinbeard AT gmail.com if you encounter any issues. Thanks!

Custom Grids and Axes in Flare

As I mentioned in my last post, I have begun a project using the Flare data visualization toolkit, and I intend to document things I learn along the way. One of the first things I investigated, after familiarizing myself with the basics was how customizable the grids and axes for visualizations could be. It took me longer than I expected to figure things out, but now that I have I would say the grids and axes in Flare are highly customizable, and should be capable of accommodating just about any needs you may have.

This post is mostly code and images, but in case you want to jump around here is a table of contents.

Background info

Before we dive in to the examples, I need to cover a tiny bit of background information and establish some constants we'll be using. First, all of the examples will be using this simple data source:

// source data
private var arr:Array = [
                        { x: 2, y: 2 },
                        { x: 4, y: 4 },
                        { x: 6, y: 6 }
                        ];

As you can see, its just an array containing 3 elements who each have an x and y property. Next, we'll look at a bare bones plot chart built with Flare. The following is essentially the bare minimum of code required to create a visualization in Flare. The default visualization is a plot chart using circular shape renderers, which is fine for our purposes here. We'll be using this code as a basis for the code added/demonstrated through the rest of the post, but I won't be repeating it all every time. Lastly, remember that Flare visualizations are really just Sprites, which means they cannot be added directly to Flex containers, only to DisplayObjectContainers, which is also Sprite's super class. UIComponent, and therefore most every Flex component, are in fact descendants of Sprite, meaning you can add Sprites to UIComponents. For more information on Flash Player's core display classes, see this page.

Base code and a basic grid
// visualization (Flare's core element)
// use Flare's Data class to convert
// our Array into a format it can use
vis = new Visualization( Data.fromArray( arr ) );

// fill the UIComponent that will be our parent
// this is a Flex app, so assume uic looks like this
// <mx:UIComponent id="uic" width="400" height="300" />
vis.bounds = new Rectangle( 0, 0, uic.width, uic.height );

// create an axis layout (Cartesian chart)
// instruct the layout/grid to use the x and y properties
// of our data elements for plotting
var axisLayout:AxisLayout = new AxisLayout( "data.x", "data.y" );
// add it to the visualization's operators collection
// (operators will be discussed in a future post)
vis.operators.add( axisLayout );

// update the vis
// (make it process and apply any pending changes)
vis.update();

// add it to the display list as a child of our UIComponent
uic.addChild( vis );

This code produces the following visualization:

Default Flare grid

As you can see, the grid bounds are dynamically created based on the data being shown. This would be very convenient if that is what we wanted, but in my case it was not.

Controlling grid bounds

If we'd like the chart's minimum values to always be zero, we can use the zeroBased property of the xScale and/or yScale properties of our axisLayout. The following code will cause both the x and y axis to begin at zero.

axisLayout.xScale.zeroBased = true;
axisLayout.yScale.zeroBased = true;

To control the maximum values of our chart we can use the preferredMax property.

axisLayout.xScale.preferredMax = 10;
axisLayout.yScale.preferredMax = 10;

Note that there is a preferredMin property as well, but it (oddly) is ignored when set to zero. You can use it to set the lower bounds of your axes to any value other than zero. Adding the two snippets above has specified that our chart axes should begin at zero and end at 10, regardless of the data being shown. The resulting chart looks like this:

Custom axis bounds
Customizing grids and axes

To really start customizing your chart, you'll want to use the xyAxes property of Flare's Visualization class. xyAxes is of type CartesianAxes and contains several convenient properties, as well as providing access to xAxis and yAxis properties that represent exactly what their names say, and are both of type Axis.

Maybe you want to eliminate the default grid pattern in favor of a simple bottom and left border.

// effectively only hides top and right borders
vis.xyAxes.showBorder = false;
// show bottom border
vis.xyAxes.showXLine = true;
// show left border
vis.xyAxes.showYLine = true;
// hide vertical grid lines (along x axis)
vis.xyAxes.xAxis.showLines = false;
// hide horizontal grid lines (along y axis)
vis.xyAxes.yAxis.showLines = false;

flaregrid_03

The xAxis and yAxis elements also provide some useful properties that we can use to further customize our chart.

vis.xyAxes.showBorder = false;
vis.xyAxes.showXLine = true;
vis.xyAxes.showYLine = true;

// distance beyond left edge of axis
vis.xyAxes.yAxis.lineCapX1 = 20;
// distance beyond right edge of axis
vis.xyAxes.yAxis.lineCapX2 = -(vis.xyAxes.layoutBounds.width);
// distance to move labels
vis.xyAxes.yAxis.labelOffsetX = -25;

// distance beyond bottom edge of axis
vis.xyAxes.xAxis.lineCapY1 = 15;
// distance beyond top edge of axis
vis.xyAxes.xAxis.lineCapY2 = -(vis.xyAxes.layoutBounds.height);
// distance to move labels
vis.xyAxes.xAxis.labelOffsetY = 20;

This code produces the following chart:

flaregrid_04

Useful methods

There is also an axisScale property on the Axis class (our xAxis and yAxis elements). axisScale is typed as Scale, but will usually be a ScaleBinding instance as Scale is essentially an abstract class. Scale (or rather its subclasses) provide two very useful methods, interpolate( value:Object ):Number and lookup( f:Number ):Object. The interpolate method will return a number representing where on the scale the passed in value falls. In our example where our range is 0 to 10, 5 would return .5, 8 would return .8, etc. The lookup method essentially does the opposite, accepting a number and returning the corresponding value on the scale, meaning .5 would return 5 in our example, 2 would return 20, and so on. These methods can be extremely helpful if you need to do custom drawing on your chart, and are the kind of value translation methods that seem to be missing from the Flex charts.

Conclusion

This is obviously not an exhaustive list of customizations possible with Flare, but it hopefully gives you an idea of the kinds of things you can do out of the box. I haven't decided which topic to cover next, so if there are specific questions or features people would like to see let me know in the comments.

Digging into Flare

If you haven't heard of Flare, go check out the demo right now. I'll wait.

Pretty cool, eh? Flare is an ActionScript port of Prefuse, a "set of software tools for creating rich interactive data visualizations" written in Java. The development of both Prefuse and Flare were led by Jeff Heer, I believe as part of his Master's thesis. I have recently begun to investigate Flare as a potential replacement for Flex charts in my current project at work and have been lucky enough to spend the past two weeks simply diving in and learning how to use the library. I needed to determine whether or not, and how easily, we can do everything we hope to on this project. My conclusion is that Flare is extremely powerful and will almost certainly support any kind of visualization we can think up.

That being said, our project is a Flex application, and Flare is simply an ActionScript library. It has a very basic wrapper component (FlareVis) that extends Flex's Canvas component, which allows basic instantiation and configuration in MXML but the library is not especially Flex-friendly. My plan is to create some wrapper APIs and higher level classes that will make using Flare in Flex much easier. What is even cooler is that our awesome client has expressed their desire for these enhancements to be contributed back to the community so that others may benefit. There is a lot of work to be done but I am really excited to start making progress. For example, Flare doesn't have specific components like a Bubble Chart, you simply have a base Visualization class that you customize and extend to create what you need. Developing with Flare has reminded me of my old AS2 days because of its dynamic qualities and freedom from the constraints the Flex framework places on you. (Note I am certainly not knocking Flex; its how I make my living and the only kind of serious AS3 work I have ever done.)

Flare works with lower level classes than you normally would in Flex, with Sprite being the core display class. This is undoubtedly one of the reasons you can attain such amazing performance with Flare. During one of my tests I animated 2000 bubbles on a chart with no noticeable slowdown or degradation, which I don't think would be the case on a Flex chart. In case you are not aware, Sprites are like single frame MovieClips in Flash. They do not have an internal timeline, but they are a direct extension of DisplayObjectContainer, meaning they can contain child objects. They of course also have a graphics property that allows you to use the drawing API to customize their appearance. They are not UIComponents, so you cannot add them directly to containers in Flex, but that is not a big deal. You can add them as a child of a UIComponent instance, and then add the UIComponent to a container like usual.

That is probably enough introduction and rambling for now, but you can expect a steady stream of posts from me about various aspects of Flare, further experiments and progress on the wrapper APIs. For more frequent and less formal updates, you should follow me on Twitter here.

Google Group for Flare

I have created a Google Group for the Flare data visualization library. Flare is currently hosted on SourceForge and their forums are terrible. I have started (and will continue for some time) working with Flare pretty extensively, so rather than suffer in silence (something I may in fact be incapable of doing) I decided to create a group somewhere better. Hopefully this better platform will help boost the level of discussion, because it is currently pretty low. If you know current or potential Flare developers, or are one yourself, please help spread the word and join the discussion.

I will soon be starting a series of posts about Flare, so if the library interests you be sure to check back soon.

Flash Camp in the ATL

Flash Camp Atlanta 2009 is happening August 28 at the Georgia World Congress Center. Whether you are just getting into the Flash Platform or you're a veteran looking for some fresh inspiration, Flash Camp will be a great one-day event with a great speaker lineup.

Greg Wilson of Adobe is the keynote speaker, and the rest of the day looks to be filled with quality content as well. Douglas Knudsen, Ben Stucki, Christian Saylor, Jesse Warden, David Tucker, Carl Smith and Leif Wells are all on the roster. The day's theme is "Enabling the Convergence of Art & Science With The Flash Platform."

The price is just $54.95 per person, or $34.99 per person for groups of 3 or more. When you consider the fact that most 3 day conferences cost $500 minimum, the price for Flash Camp is an amazing deal. I unfortunately can't make it to the event, but I hope to make it to a Flash Camp in the very near future.

Disclaimer: I'm employed by Universal Mind, an elite group of technologists who excel at solving the difficult challenges of building and optimizing rich internet applications, and also the primary sponsor of Flash Camp Atlanta 2009.

Swiz example application with Presentation Model pattern

About a month ago I was introduced to the Swiz application framework for Flex. Within an hour or so, I was not only sold on the simplicity and effectiveness of the framework, I was digging around in the source adding features. Shortly after that I started collaborating more closely with Chris Scott, creator of Swiz and a coworker of mine, and Sönke Rohde, the other Swiz team member. The three of us have been cranking away adding new features ever since and have a lot planned for the coming months.

Now that introductions are out of the way, let's look at some code. I'm really not going to try and explain much of anything here because I've done that (heavily) in the code and comments of the application. In the recent past I have repeatedly found myself frustrated with a lack of examples when reading about new frameworks or projects people are promoting. I learn best and quickest when I can see something in action and figure out how it works, so I created this example for other people like me. If you have questions, comments or suggestions about the application you can obviously post them here, or you can post them in the Swiz Google Group where I will also be posting a link.

Lastly, a couple of disclaimers.

  • Only the Employees view of the application contains anything. I only created multiple tabs to facilitate the mode monitor at the bottom of the app.
  • I've placed the ASDocs above the metadata tags for the sake of readability and simplicity. In a real application the ASDocs (unfortunately) go between the metadata and the code.

Application :: Source