Category: ActionScript

  • There is Nothing Wrong with Learning AS3

    I’m writing this post out of guilt. I’m working with a contractor today, Charles Schulze, helping him get a working version of one of our API’s. He’s been really patient with us while we get a working build to him that he can build around. We’re all in this walled off area of desks and tables called “The Pit”. It makes it easier to collaborate compared to f’ing cubes. A discussion was going on about AS2 and AS3 differences. Charlie again mentions he wants to get more projects doing AS3. He doesn’t get as many as AS2. I told him if he is doing pure ActionScript 3 all the time, he should be doing Flex work instead of Flash. He laughed.

    “Dude, you’re using classes in ActionScript 2… you’re building a mini-app. If you know ActionScript 3, you’re practically an application developer.”

    He then looked upset. He didn’t show it, but I could see it. He brought up various scenarios, so I did my pitch on what I think Flex is for and what Flash is for (typically). I threw in the caveat it’s not always that black and white, especially with hybrids like him who can design and code equally well. If you are in a particular industry, it makes it easier to focus on a skill set. For example, if you keep hanging around the agency world doing contract, you’re more app to get bling using your Flash skills. While I’m sure they’d ask for AS3, a lot of OOP and design patterns are useless when you have a week to get stuff done that would take me 2 months. Vice-versa in the software world in using Flex. A lot of the design appreciation just isn’t there, and you cannot use a lot of the skillsets that don’t apply to coding.

    He brings up more postulate scenarios, such as doing interactive, design-driven websites. As if on cue, Nick throws in the “doing 3D interface work”. Yeah, I was owned… but I still didn’t think that was justification for putting AS3 in a product meant to encourage upgrades, which then encourages stock holders to see post-merger success, and thusly purchase more stock in Adobe. I look at Flash 8 and go, “Damn, they got that one soooo right. Phat design additions and re-implementation of Script Asisst. Macromedia for the win!”.

    He then mentions quietly with a resolute sadness, head down working on his computer, that I made him not as motivated to learn more AS3 than he already knows. I immediately felt bad, like I had erred in communicating and then spent the next 5 minutes un-doing… or rather, re-directing my rallying towards learning AS3 in Flash CS3, not Flex Builder. Sapping passion from another is a major sin.

    I explained the immediate benefit of runtime errors. Yes, that dialogue box in your face can belt your self-esteem at times, but nothings more frustrating than an error that just stealthily never appears. Now, you see them when your SWF is running, AND can see the path leading up to their cause of failure. Furthermore, you’ll never have that nagging feeling of “maybe I should optimize my code…”. AS3, when used even with an once of effort towards using strong typing gives you mad speed increases. This won’t necessarily improve your animation speed, but certainly won’t detract from it, especially in games, or complicated menu systems. The days of seeing “Why does ‘parseXML’ freeze my animation?” on mailing lists should be a thing of the past. E4X is slower than DOM (aka XML.childNodes ) … but typically uses less code. Finally, the increased cleanliness of the strong-typing implementation will ensure your code probably works right when you compile, better than AS2. This confidence makes you a better Flash Developer.

    Let’s not forget the most important… file size. Flex 2 SWF with a Button component, 126k. Flash CS3 SWF with a Button component, 15k. That assumes your even using the new CS3 components; one you could could be smaller for example. Both Flash CS3 & Flex 2 produced Flash Player 9 AS3 SWF’s run the same speed: fast as nuts.

    So, I hope I got Charlie psyched again about getting more AS3 projects. I felt like a dick stealing his joy on wanting to get more into it, and felt I made a valid, applicable case to him to get him back in the mood for it. Hopefully my frustrations at feature choices won’t detract you either. You can learn AS3, reap the rewards, and steer clear of all the OOP & design patterns if you so choose. AS3 alone is still pimptastic in Flash CS3. There is nothing wrong with learning AS3. Just remember AS1 and AS2 are still powerful and a valid part of your arsenal.

  • Making a Cooler Preloader in Flex: Part 1 of 3

    Preloader Preview

    Preface

    Preloaders in Flex are not like preloaders in Flash. Gone are the days of the 1 liner:

    if ( _framesloaded < _totalframes ) gotoAndPlay ( 1 );

    We now have base classes and setter properties. While you may have to write a class and then set that class on your Application’s preloader property, it’s really pretty easy once you do it more than once. This tutorial will show you how to build a preloader in Flex using a Flash built animation.

    Introduction

    Flex’ built in preloader is pretty sweet. It auto-adjusts for your application’s color to stand out, it handles all aspects of preloading. This includes remote shared libraries, fonts, and even deferred classes used in modules. Finally, it deals with the initialization of your Flex application which can possibly take longer than a few milliseconds.

    If you are building branded applications, every little detail counts in enforcing your brand identity upon your user. You want to remind them the positive experience they are having was brought to them by you. Nothing is more important than a first impression, and the first thing people see in a Flex application is the preloader. It is important that you spend adequate time on making it look good and consistent.

    To make a custom preloader for Flex, you have to do 2 steps:

    1. Write a class that extends DownloadProgressBar
    2. Set the preloader property on your Application class to your preloader class.

    No witty 3 step process here.

    The purpose of extending DownloadProgressBar is to handle the various things that happen in the life cycle of preloading (yes, we have life cycles now, not just downloading of bits). You do not have to handle anything save the FlexEvent.INIT_COMPLETE. You could for example put some dots who are ridin’ spinnaz and that’s your preloader.

    …or, you could handle all events, and duplicate the Flex one with a different design showing the download & initialization progress.

    The steps for making a custom Flash Preloader for your Flex app are as follows:

    1. Make a 100 frame MovieClip. TextField optional (as is everything).
    2. Give MovieClip linkage ID with no class name.
    3. Compile your SWF (“Test Movie”)
    4. Write your own Preloader class in Flex Builder which uses your Flash MovieClip.
    5. Set the Appliction.mxml preloader property to your custom class.

    Making Your Flash Symbol

    In Flash, you make a MovieClip that is 100 frames long. This will be the preloading part of your preloader, the MovieClip that shows the progress of the SWF downloading. Notice I have both a 100 frame animation as well as a dynamic TextField. The TextField will have the percentage numbers (i.e. “73%”) put into it dynamically.

    Notice, also that the TextField has an instance name. This is so I can target it with code. Keep in mind, even though we are giving the TextField an instance name, we’ll be targeting it with code in Flex. We won’t be writing any code in Flash.

    Finally, I wrap my preloader in a MovieClip because I want the preloader to fade out when it’s done.

    I make sure to give the preloader an instance name so I can “dot dot down” to the preloader through the animation. Dot dot down is Flash slang for using dot syntax to walk down the display tree to target a MovieClip you want to interact with via code. In our case, it could be:

    _root.my_clip.preloader.amount_txt.text = "70%";

    Omg, I used _root, lol, l@mz03, me fired.

    Finally, you export your Symbol with a linkage ID. Exporting as Flash 8, AS2, you just fill in the linkage ID class. Don’t export as Flash 9, AS3. If we did that, we might as well write the class for the preloader , and that’s just too much work, and too much added file-size for a class that’s supposed to be simple and most of all lightweight. If you are using Flash CS3, just change your publish settings to Flash 8, AS2 or AS1.

    Flex will look for this linkage ID name when you are embedding the MovieClip. Now compile your SWF and your done.

    Custom Preloader Class

    You then write your own Preloader class. Have it extend mx.preloaders.DownloadProgressBar. There are multiple ways to embed Flash content. For our purposes, we’ll embed to a class property.

    If you look at the Preloader’s setter function, you’ll see we get a Sprite (1 frame MovieClip) that emits all the preloading events we’ll care about. In this case download progress, when the SWF has finished downloading, when the SWF starts to initialize classes, and when initialization is complete.

    Our download progress & SWF download done functions will dig down into the Flash MovieClip, and show download progress in both the text field, as well as making the preload MovieClip symbol animate via gotoAndStop based on the download percentage. Since download percentages are 100%, it makes it pretty easy to figure out what frame to go to.

    The initialization ones just show “Initializing…” in the TextField.

    Unlike most Flex preloaders, we want ours to animate when done, and only THEN actually launch into our Flex application. You can accomplish this by not dispatching the complete event. Dispatching this let’s the Flex application know the preloader is done. In our case, we want to wait till the Flash animation is done before doing so. We add a framescript ( a function called when the Playhead reaches a frame) to frame 21. When the animation is done, it’ll hit this frame, call our preloader class’ function. This will stop the animation and dispatch the event, letting the Flex application know we’re ready.

    Conclusion

    That’s it! Keep in mind it’s hard to test these things locally on your box. In Flash, we have the bandwidth profiler, but there is no such thing in Flex. You can either use network throttlers, like Charles. Alternatively you can upload the files to your site, install the Firefox Web Developer Toolbar, and choose disable cache.

    In the next part, we’ll be taking advantage of Flex as a statefull client, and getting all the data you need. This takes time, so we need a cool way to show this to user as well as making it fail gracefully.

    Flash Preloader in FlexExample | Source | ZIP

  • Flex Controlling Flash

    Preface

    This article focuses on controlling applications written Flash Player 8 and below that are loaded into Flex at runtime. If you want to read up on the various ways of doing this, I’ve written in the past how to control Flash Player 8SWF’s in Flash Player 9’s new AVM. This article specifically will talk about using Flash Player 8 content in a Flex 2 environment.

    Before you read further, I strongly suggest you beg those in charge to allow you to re-write the AS2 content in AS3 (Flex 2 or Flash CS3). If that fails, keep reading.

    Use Cases

    Here are some common use cases where one would want to load Flash content into Flex content:

    1. You have some existing Flash content that was previously written for a Flash Player before 9 (8, 7, or 6). This content could be a fully functioning application that has already proven itself by working successfully for awhile. Therefore, you’d like load it in atruntime and let it do it’s thing. There is no time, budget, and/or resources to re-write the content in AS3. An example would be a video player written for Flash Player 8/7/6 customers (those who don’t have 9).

    2. You have some content that was created by another company or 3rd party tool that you want to integrate and possibly control. This could be SWF’s generated by Captivate, Connect, Swish, or perhaps even older versions of Flash. There technically are no “source files” so you couldn’t necessarily re-write the content, or said content just couldn’t be created in Flex in the first place.

    3. You’re a Flex Developer and have no intentions of learning Flash. You’ve been ordered to load SWF’s that are not AS3 and control them.

    4. Like #3, except you can’t find any Flash Developer contractors that are available. Imagine that.

    For the record, all 3 are valiant efforts fraught with peril. Knowing this, you can re-attempt my advice to plead with management to abandon the course in folly, or grit yer teeth and git-r-done. I won’t re-iterate the problems here, you can read that in the above link. I will, however, give a quick refresher on what you can and can’t do.

    First, none of the above scenarios allow embedding. If you do not have the source FLA created in Flash, with a valid copy of the Flash authoring tool (MX, MX 2004, 8, or CS3), you have no choice but to load this stuff at runtime. If you DID have a copy, you could embed it. Embedding AS2 SWF’s, however, removes all of your code. Thus, embedding AS2 applications won’t work. You don’t have these problems with AS3.

    Second, loading AS2 / AS1 content at runtime creates a separate, special security sandbox for the SWF that’s being loaded. The DisplayObject is called AVM1Movie, and he’s an iron-clad, impenetrable black box. There is physically no way to breech it via ActionScript 3 to talk to it. You can, however, useliasons over / under the wall via ExternalInterface or LocalConnection. ExternalInterface sucks because it uses JavaScript. Every project I’ve ever done that incorporated JavaScript as a necessity added 1 more level of complexity, extended the debugging time in the project, and overall made it more challenging to make progress. Thus, while theAVM’s may be different versions, at least we’re coding in a semblance of the same language and runtime… well, more than JavaScript anyway. AS1 and he may be similar , but at least AS1 works the same in all browsers. You already have enough challenging things to worry about now that you are down this dangerous path; you don’t need another headache.

    Third, your AS3 content cannot immediately “get rid of” AS2 / AS1 content in this AVM1Movie thing. Garbage Collection will get it when it feels like it. In the AS2 / AS1 AVM, removeMovieClip for the win! It works immediately, and while the actual RAM of the used variables may not go away, all media stops (sounds, video, animation) as opposed to AS3 where you have to be explicit to do so, not just remove it from theDisplayList.

    Solution: A proxy SWF, aka proxy.swf, aka, a Flex liaison to AVM1 content.

    Why a Proxy SWF

    Since Flex 2 content (Flash Player 9, AS3 AVM+ SWF’s) cannot tell AVM1 SWF’s what to do, they use a guy on the inside, a proxy.swf, to act as agents for them in that world. The proxy.swf executes the orders that Flex issues, and these orders are communicated via LocalConnection.

    That downside is, you still need to code this proxy.swf in AS2 or AS1 and compile it for at least the Flash Player 8 or below. You don’t necessarily need Flash to do this. You could use MTASC, PHP’s Ming, or JGenerator (I think what Lazslo uses?). I haven’t gotten this to work myself, but you could also possibly use the Flex 2 SDK’s mxmlc with the “as3” compiler option set to false, and the “es” option set to true. This should generate a Flash Player 9 SWF that uses the old AVM (so… technically AS2 like code that’s compiled to AS1 bytecode using a Flash Player 9 compiler).

    …or, you could use my generic compiled example, and hope for the best.

    If you want to do it right (keeping in mind “right” here means not-so-right since we shouldn’t be using older SWF content anyway), you typically tailor a proxy.swf for the particular content you are loading. For example, if you are loading Captivate SWF’s, you build a proxy SWF that can:

    1. load in Captivate content
    2. control Captivate content by their *hidden API
    3. unload Captivate content

    * For more info on hidden API, go here, scroll to the bottom and download the big ole PDF, search for “rdinfoFrameCount” which should take you to the “Controlling Adobe Captivate projects with variables” section.

    This, as opposed to just my generic proxy that just accepts methods as strings and runs them much like JavaScript’s eval. That way, you can expose a loose API. You can’t share AS3 and AS2 interfaces, but we’re already past the point of IDE help here, so you’re really doing faith based coding at this point. Anyone whose ever used a dynamic language (as opposed to strict typing) shouldn’t have a problem with this. If you don’t code the proxySWF specifically for the content you are loading, it’s harder to debug, and basically really hard to identify which remote method invocations are failing.

    I’ve provided 2 examples at the bottom of this article. One is my generic “I’ll run what you send me” one and the other is one built specifically to control the Flash 8 Video Player. While the generic can be something you can build upon to support your content, I highly recommend you follow how the video player one is built and build the proxy.swf specifically control a specific SWF.

    How It Works

    They both work the same way.

    1. Flex SWFLoader loads an AVM1 proxy.swf
    2. proxy.swf loads the content it’s supposed to use via loadMovie / MovieClipLoader
    3. once the proxy.swf has loaded it’s content, it let’s Flex know
    4. at this point, Flex can now tell the proxy.swf to do things with the content it’s loaded

    These can sometimes breakdown. LocalConnections are by their very nature asynchronous. While you can create an instance immediately, that doesn’t mean it’s immediately available for use. For example, the AVM1 version of LocalConnection gives you a Boolean so you know if the send actually worked. If you get a true, it doesn’t mean it actually sent, just that the send operation itself “worked”. Amazingly f’ing useless. Send again? Hell… WHY NOT!?!

    The AS3 version is different. You can get a few different types of exceptions from sending messages, such as ArgumentErrors and AsyncErrors. While the docs claim that your syntax can be correct, and it could be your request is just bigger than 40k, this is a crock. Even simple strings can just fail, and then magically work later. In short, LocalConnection is flaky; you’re code should compensate. If you need ensured communication, use ExternalInterface. That, however, has it’s own can of worms.

    You do not have to use a SWFLoader. You could just a Loader, but since Flex is UIComponent based, SWFLoader is UIComponent based, so there you go.

    The proxy examples I have both use MovieClipLoader. While you could simply use loadMovie, MovieClipLoader gives you more events to understand what’s happening with your loaded content. You don’t have to write polling code yourself; instead, you have dependable events that fire. The only one you really care about is onLoadInit. When that fires, whatever SWF you are loading can now be accessed by code in an ensured fashion. This is why you wait for that to fire as opposed to onLoadComplete.

    LocalConnections

    All of this communication between Flash & Flex is done via 4 LocalConnections; 2 in Flex, 2 in Flash. LocalConnections are only 1 way. Meaning, you can only send messages or receive messages; not both. I typically use the “in_lc” and “out_lc” naming convention; feel free to make up your own. The Flex out_lc talks to the Flash in_lc. Vice versa, the Flash out_lc talks the Flex in_lc. The only thing uber confusing is that in Flex, the names are reversed. Since LocalConnections connect on a “connection name”, these 2 names need to be the same in Flash & Flex. So, in Flash I have:

    LC_IN_NAME = “_JXLFlashProxy_IN”;
    LC_OUT_NAME = “_JXLFlashProxy_OUT”;

    And in Flex, I’ll have the same thing for values, but different things for the names; just to help easy the insanity.

    public static const FLASH_LC_IN_NAME:String = “_JXLFlashProxy_IN”;
    public static const FLASH_LC_OUT_NAME:String = “_JXLFlashProxy_OUT”;

    The only difference is in Flex, you use the OUT name for your Flex “in” connection. Since Flash is sending messages out on the OUT connection, Flex needs its IN connection listening to the “Flash OUT” connection name. The reverse holds true for Flex sending messages. He’ll send them on Flash’s IN connection name.

    To reiterate, these messages are asynchronous. They don’t arrive immediately, and you cannot return values. You can treat it like events, where the LocalConnection in Flash can send a message back to Flex with data, but unlike events, you can’t depend on this; some messages just don’t make it.

    Dynamic Flash

    If you are not familiar with Flash, you’ll notice that both AVM1 examples just dig right into the SWF they are loading. This is because there is no runtime strong-typing in pre-Flash Player 9. For example, if you look at the video_player2.fla, you’ll notice some methods on the main timeline. Flex asks the proxy.swf to call those methods since he can’t. Like a kingpin asking a thug to get his hands dirty. I can access those methods as if they were public class methods… even dynamically by concatenating strings together in Flash Player 8 and below. This is where a proxy.swf shines in that since it’s made in dynamic Flash land, it can play by dynamic Flash rules. This is important because sometimes you’ll be loading SWF’s that you don’t have code control over, and need to jury rig them to do things they weren’t originally intended to do.

    Keep in mind a proxy.swf can do more than just dynamically call methods and set properties on a load SWF application. It can also affect the nature of that application. Since you are still in a prototype based language, an object’s prototype property is writable. Thus, even if you don’t have the source, and don’t feel like using aSWF decompiler to get some form of source, you can overwrite prototype objects that you introspect to force the SWF to do things you need.

    …you know, in writing all of that, I’d much rather use a proxy.swf with ExternalInterface. As much as I hate JavaScript, it was pretty easy to break LocalConnection. Maybe next weekend…

    Source Code

    Video Player Flex Example – Example | View Source | ZIP

    Generic Flex Example – Example | View Source | ZIP

  • Building Tracer Bullets with Flex Builder

    Skip to “Flex Tracer Bullets” to bypass all the philosophy and justification.

    Preface

    The Pragmatic Programmer, a must have programming book, talks about using Tracer Bullets to help clarify and further define requirements. In military terms, a tracer bullet is a special round of ammunition that burns brightly when fired from a weapon. It’s every few rounds, so not every round is a tracer round. It is very easy to see, and thus the person firing can adjust their aim accordingly. In essence, you build an early version of your software that matches the client’s requirements as closely as possible, and get it to them as quickly as possible. The Pragmatic Programmer makes special note that Tracer Bullets are different than prototypes. Prototypes are usually disposable whereas Tracer Bullets are built with the understanding that they will eventually be used in production level code.

    If you’ve read any of the Ruby on Rails books, one thing they espouse is client involvement. Getting the client something tangible to see and play with in mere days. The “play with” is important. Many times in my career “comps”, visual wireframes with some design treatment used to illustrate the entire application, have been treated as the front end developers final requirements. They never end up being this, are never thorough, and resist change (because of the expectations of them). A picture of an application, and an actual application are 2 different things. Giving the client something tangible, that appears to work like the real application, gets them as close to the application as possible. This intimacy generates the most valuable feedback you can get next to user testing. The difference is, this is pre-launch feedback, so you can implement it before you deliver.

    This is important, not just because the client is actually happy the day you deliver the final build of software that meets their expectations, but because of all the bad things you’ve prevented. I’ve read and heard many stories about how weeks were spent in development going down a path the client approved, only to head off exactly the reverse direction for another few weeks, with extremely frustrated developers. Worse than that are the miscommunications , whether by the telephone effect, or the mere lack of anyone I’ve ever met to actually effectively extract customer requirements that are factual. You then think you are going in the right direction, only to have the client say that wasn’t what they were looking for at all.

    Bottom line, it’s better to spend 3 days hashing out some ideas with fake data in your code for sales or the client to see and play with rather than 1 week on requirements gathering, and then 2 weeks in development. The problem with the latter is that you have no guarantees the requirements didn’t change, they were accurate in the first place, or the client will even like what you’ve done even if the requirements and what they wanted were one in the same. Requirements and software are 2 different things. Furthermore, even if you are agile to changing requirements, requests on paper and experiences using software are vastly different as well. In the end, clients are paying for the latter.

    I’m pretty harsh on requirements, I know. That’s because my personal philosophy is, “What do you want the software to do?”. Once told, I go build something, show the client, and go from there. Using early builds (a build meaning a working version of the current, compiled code) as tracer bullets has worked well for me. Sadly, I haven’t found out how to get tracer bullets to work for fixed budget projects. When you don’t even have time for a prototype, you usually just have to rely on your experience and hope you have aim like a sniper.

    You build a tracer bullet, an early & working build, to give to the client and let them use it. You garner feedback, and adjust your direction from there.

    Flash vs. Flex, Prototype vs. Tracer Bullet (again)

    Flash Prototypes

    If you would of asked me a year ago what’s the best way to do tracer bullets, I’d probably have said take a hybrid approach. Build a Flash prototype, and if the client digs it, you can then transition into production code once your direction is more solidified. You can then show them builds every few days (or Thursdays so they can play with it on Friday). The cheapest and quickest way I’ve seen this work is to have a Flash Designer work with the Interaction Designer/Information Architect (maybe they are all the same person), and produce a series of working screens in Flash. The data is fake, but the buttons do in fact work. These are most effective if you can even have some simple use cases working as well.

    For example, if the user needs to “create something”, the prototype will actually have the data the user inputted into the forms actually update a DataGrid for example. Even smoke and mirror effects such as this work wonders with sales and real clients in my experience. Most don’t really care the data isn’t live, and you even run the risk that prototypes are fraught with: that they are perceived as a real application, and are immediately latched onto. At that point, you better hope you can duplicate all of what the designer created in production code. Common problem, but a good one. The biggest point of contention was getting a Flash Developer who could duplicate accurately whatever the Flash Designer had created.

    It’s even worse nowadays for some Flex Developers. As our industry grows and we start taking on traditional programmers who are skilled at code, but do not have a lot of the multimedia experience a lot of Flash Developers sometimes have, a lot of Flex Devs shudder when they just even get complicated “looking” design comps. It’s one thing when your IDE has a timeline, and boilerplate level graphical control, but it’s completely another when you are at the mercy of the component framework you are building upon. Component developers will scoff at this notion, as it is definitely true that you can build components around any design. Either way, those things take time, are not easy, and are typically code centric vs. design centric implementations. It’s even harder when your tool wasn’t designed for it.

    Bottom line, I’ve seen a lot of value in Flash prototypes. Pre-ActionScript 3 is more loosely typed, and Flash is a RAD tool, allowing you quickly build working applications with tight design control, even if “working” is faked. The product of this work makes a great shock troop; quickly in sales/the client’s hands, with next to immediate understanding of how on/off base you are.

    Rapid Application Development isn’t Bad, it isn’t Good, it just is

    Flash prototypes work for more design centric RIA‘s as opposed to larger scale applications. This is because these types of applications, such as an online banking application, or a financial planning tool, are usually business driven. This means the visual aesthetics are usually the least important part of the entire project. For the record, I hate that and strive daily to change that. Yes folks, it IS possible to have a financial planning tool that not only provides sound advice on your economic future, but looks hot doing it. “R” in “RIA” for the win. Regardless, the default Flex components work wonders in looking “good enough” for any application. With working functionality, they shine.

    Flex Builder 2 specifically on it’s own, however, isn’t as RAD as Flash with regards to design projects. I’d argue the reverse for business projects. Either way, both allow you to end up with something that you can use later if coded with as much best practices as possible given the time constraints. This is key because I’ve seen a lot of blogger comments critical of the “RAD” term, feeling like they’ve been sold a bill of goods. They immediately perceive RAD as un-scalable and I don’t think this is fair. They are immediately implying success.

    Let’s take Twitter for example. A few in the blogsphere used Twitter’s performance issues as proof in the pudding that agile/rad languages/frameworks may get you something that works quickly, but that working application doesn’t work well under pressure. I liked the counter argument one commentor, John Ballinger, posed as a rhetorical question in this blog entry (scroll to comments):

    Could Twitter have used any other language (YES of course) but would they have been able to build it in the time and been agile to the constant changes that “may” have ultimately lead them to the current explosion of traffic they have today?

    What I believe John is implying here is that by using a language & framework that allows them to produce a good and working product quickly, they become victims (in a good way) of their own success. If they weren’t quick to market with the flexibility to respond quickly to their users, they wouldn’t be in the situation they are just getting over now because they wouldn’t have a mass of users to begin with. Bottom line, I’d much rather have scalability problems that I can solve with my teams’ programming know-how vs. a scalable site (in theory) with no users. No one cares about scalability if you’re not successful… after the fact anyway.

    Going with RAD (rapid application development) really meaning what it says and not being inherently evil, just being what it is, I believe Flex is a RAD tool just like Flash. The difference here is using it to write code that is a good foundation.

    Flex Builder Tracer Bullets

    So how do you write Flex Builder Tracer Bullets knowing that Flex can be a RAD tool and Tracer Bullets are good to do? Here’s 2 lists:

    Technicals

    1. Don’t use ActionScript, use MXML
    2. Use states, don’t use transitions
    3. Write strongly-typed ValueObject’s based on client’s data needs
    4. build workflows, then build use cases
    5. use copious amounts of tagged builds in Subversion (or whatever source control you use)
    6. componetize sections
    7. use Canvas first, Panel later
    8. make builds easy to see
    9. use fake data from real ValueObjects
    10. put event handlers in Script tag, not in MXML

    Esoterics

    1. Find in a friend in sales (or a stakeholder at your client)
    2. Write emails to stakeholders (sales/client) that ask a question that can be answered
    3. recognize opportunity, and take it
    4. use a phone, not email or IM

    Don’t use ActionScript, use MXML

    Flex Builder can render MXML components pretty accurately whereas ActionScript components not so accurately. This means you can see, in the Design View, your application as it’s coming together. This includes GUI controls and your use of states. Having to compile your app just to see one component visually is slow. Build in MXML because it’s faster to write, and faster to see.

    Use states, don’t use transitions

    A lot of screens have specific states. Some have none. The majority, do, though. It’s quicker to make 1 LoginForm with 3 states than 3 different MXML views that make up a LoginForm. Quicker to edit, too. Flex Builder can show you those states visually, and automatically write the code for you to add & remove controls as well as changing their properties when the state changes. It’s always easiest to start with “main_state”, and go from there. If you don’t, you may later have to copy and paste MXML you’ve already written into AddChild tags individually which are themselves in state tags. Total pain the arse. Do it right the first time.

    Transitions, the animated changes between states, add a lot and make the user’s eye-focus putty in your hands. Don’t do it yet, though. Wait until you’ve gotten direction on your app before you start directing the user’s attention. Transitions are probably the most volatile code in your application, and are also the most subjective. Finally, they cause unexpected changes later when you start throwing data at components that causes their state to change (like custom item renderers for example).

    Define clear states for each View (component), and build them using Flex Builder. It’s ok to hand type MXML as well.

    Write strongly-typed ValueObject’s based on client’s data needs

    Understand the data you have, as a client developer, early. Whether it’s coming from your server team, the client’s server team, or both, understand what you are going to be able to represent that data model in a strongly type set of classes. These do not need to match the server, and new ones can be created specifically to make GUI development easier, including properties. Getting these done allows you to be build View’s (components) that actually have accurate GUI controls on them to represent the data. No VO’s, and your just guessing. VO’s give your GUI design direction, give it purpose.

    If there is contention in the VO’s, you have a communication problem. Solve it, learn the nomenclature, get the lingo down. Collectively agree with all parties involved to have 1 name for everything. While some developers will say 2, “We call it an asset ID, but the customers call it an item ID” you’re just making it more confusing for you in meetings, emails, and IM’s. Bad communication will sabotage any project, and clear data is the key.

    If they are strongly-typed, when you decided to re-factor, you’ll get compiler errors in Flex Builder which makes it easy to quickly change names in places that your global find and replace didn’t catch (or if you were just too paranoid to do so, by hand). In this way, you’re application is resilient to change… and it’s not even really an application yet.

    build workflows, then build use cases

    A task that the user needs to accomplish is solved by an effective workflow. A workflow is the way a user accomplishes that task by being guided or “led” via the user interface. These are the most important parts of an application, and need to be nailed down first. They are also the first cement to dry when coding your application (meaning hard to change later without drastic consequences) so it’s best to really think these out based on sales/client dialogues. More is better. If you have more than one idea to make an interface that allows a user to create a widget, go for it. If it’s up to your Information Architect or Interaction Designer, let her/him know in no uncertain terms the clock is ticking.

    Once you get a workflow down, “The user is shown a list of their savings plans. They can then interact with these savings plans”, it’s now time to build use cases around them. The user needing to upload a file is one, the user needing to be able to filter visible data is another. Use cases are things the user needs to do. They usually collectively make up the task the user needs to accomplish. Sometimes, they can be task in and of themselves. The point here is to ensure you have a solid workflow first, THEN start working on satisfying your use cases.

    Both should be put in builds and thrown at your client with abandon. It’s ok to walk them through it in guided demos; this is brainstorming, not user testing. This is how your application will effectively work, so make sure you client can do what they need to do and can see what they need to see.

    use copious amounts of tagged builds in Subversion (or whatever source control you use)

    If you get a working build with specific functionality, make a tagged build in Subversion. If you are not using Subversion, mark the current build in your repository with a special label (in CVS), or some other verbose comment with an accepted convention so you can find that exact build of code later. No source control? …just make a copy of the code.

    This way, if you or the client wants to refer to an older example, you’ve got the mofo on ice, and can thaw it in minutes, ready for any meeting.

    componetize sections

    This has less to do with OOP, and more to do with MXML readability. Because Flex Builder is nice in that the Design View will write all the code for you via dragging and dropping controls on your forms, it doesn’t have that human touch. So, even if you don’t format it by hand, you’ll still end up with a ton of MXML tags spewed out over hundreds of lines if you build an entire application in one MXML file. The first pure MXML app I ever saw in my life was a pure MXML RSS Reader posted on Flexcoders. While I respected MXML’s power, I couldn’t read it for $h1werwer….

    If you have a big form, put it in a component. That way, 30 lines of MXML becomes ““. Omg, 1 line of meaningful code… hells yeah, I can read that at light speed! Furthermore, if you hold Control (Command on Mac), you can then click on “UserForm” as a hyperlink, and open the file in question. Supa-fast!

    use Canvas first, Panel later

    While Panel gives you a nice container for your mini-components of your application, they merely serve as pretty looking trappings for your lack of requirements insecurity. Use Canvas, set horizontal and vertical scroll policies to off, and let it be raw. You need to see the gaping holes in your UI, not hide them in pretty chrome.

    make builds easy to see

    The point of builds is to get client feedback, and get it early with real software. If the client can’t see the software iteration, they’ll question “this whole ‘Agile’ thing”. Don’t send EXE’s over email, nor SWF’s. Find a reliable FTP site, upload it, and run it. This is easiest if you don’t have any local file dependencies, the SWF makes no data calls (locally or externally), and doesn’t require any weird arse things to make it run (“Oh… well, lemme reset my host file to be localhost, and then reploy the war file…”. What? Dude, just upload the SWF with accompanying HTML file. If you can’t do that, you’re not writing a Tracer Bullet, but instead a real application build that wasn’t meant to be agile.

    If the sales person/client can’t see the SWF, neither will your users. If you don’t want to deal with Flash Player install issues, don’t do Flex development. Once you get it out of the way, you can always depend on your salesperson/client being able to see your latest build from there.

    use fake data from real ValueObjects

    A great way to point out immediate problems, and make make your application feel more real, is to throw fake data at it in the form of ValueObjects populated with data. Obviously, you may be way ahead of the server team (yours or the client), so it helps to have factory methods; functions that can generate a bunch of fake data for you quickly. You can then throw this at the GUI time and time again to test something. Pain in the neck to write, but you’ll use them a tons afterwards.

    Furthermore, this ties in really well with the “make builds easy to see”. Instead of praying that your database call works while the client is viewing your SWF, or if the back-end guys will have their code done by the meeting, you instead don’t have to worry about it; it’s embedded in the SWF, and will work even if the Internet connection suddenly dies (after they’ve downloaded the SWF).

    For Cairngorm, a technique I learned from Darron Schall was using “Mock Commands”. You make 2 Command classes; 1 for real data that may use a Delegate to make a call to the server, and 1 that just gets fake data from a Factory class and has a timer to simulate a delay. That way, you just change 1 line of code in your Controller class to switch to fake-data mode.

    put event handlers in Script tag, not in MXML

    The thing that’ll change the most as you hop around files modifying GUI stuff is your MXML. Since most MXML is for showing GUI controls, it’ll be volatile from the get-go. Putting code there is just asking for it get in the way, and maybe even get waxed. So, instead, have your Buttons for example call a function in your Script tag for their click handler instead of do things directly in the MXML. That way, you can even delete the MXML, replace it, and then easily wire it up again.

    Find in a friend in sales (or a stakeholder at your client)

    Sales can go either way. They can be a developer’s worst enemy, or you’re biggest fan base. I prefer the latter. I’ve been in too many situations where sales sold something that was impossible and I had to make the impossible possible. AKA, “Flash Developers at Design Agencies”.

    The first thing to do is find out who in sales (assuming just 1 individual) is interacting with the client, and basically catering the project to their needs. Start up a dialogue with this individual assuming your project manager doesn’t mind, and get to know the client. You may wish you hadn’t, but do it anyway. Learn the needs that sales is trying to satisfy by using your code as a conduit. When they start asking for specific functionalities, you’ll know why, and be more informed in suggesting ideas, changes, or options.

    The ideas are cool because sales usually perceives engineering being “fun governors”; depending on the organization. The last thing they expect is MORE things for the developer to do coming FROM the developer. The changes are good because as an engineer, you know how hard something will be to make, how it may work differently in practice, or know the ramifications of a design path whereas sales might not. Rather than saying no, you can make an informed suggestion about how to get the result sales is looking for. This may seem like something you can do in a meeting, but trust me, it’s tons easier when you already have an established rapport with the individual, and almost give the suggestion in passing, almost like you and the sales guy have already got it all planned out.

    Finally, options are key here. Being successful at software is the middle ground between doing everything sales wants, and coding just enough to get it solid and working. Enough flair to make the sale, enough OOP to ensure it doesn’t blow up. Combined, you win. A lot of times, you as a developer may not know what that balance is. The easiest way I’ve found is to put the ball back in sales or management’s court. If they ask for 5 things, you spec them out, give time estimations with risk assessments, and any additional optional ways to implement certain features in increments. Giving sales options is way better than ultimatums. It’s important that your time estimations for your articulated options with possible incremental milestones are not bs. You need to be sincere, honest, and thorough. If it was easy, they wouldn’t call it “work”.

    Naturally becoming friends with the client is dangerous. It’s all fun and games until business gets involved. That doesn’t mean you still can’t build up a rapport to better communicate with the client, and thus understand where they are coming from. I’ve seen a lot of managers in my time offer to shield me from meetings. If the meeting is with the client, I highly recommend you lower shields, and go. Even if you don’t converse in a dialogue, you can still listen.

    Write emails to stakeholders (sales/client) that ask a question that can be answered

    When you are in the process of figuring things out, it’s really easy to give that laid back, relaxed feeling others in conversation. The no-pretense, “What do you think?”. Don’t ask open ended, non-focused questions like that to stake-holders. Be direct, and know the type of feedback you want before hand. If you do, 1 of 2 things will happen, both of which are good. Either the salesperson/client will answer your question in written form so you can refer to it later and thus continue working on your GUI, or they’ll have no clue, in which case you can propose some ideas and look straight pimpin’ (really smart and capable).

    recognize opportunity, and take it

    If your sales/client has no clue what any form of Agile is, or what a “build” is… find a way to educate them. That is, find an appropriate time and place to introduce the concepts. Don’t start ranting about Agile Development on a sales call for example. Instead, if you have a question about how a certain section works on a design comp the client sent you, use that as an opportunity to send them 2 builds, and choose the one they like, or perhaps choose a different one. If they respond positively (or not negatively), boom, you win. You just set the expectation you can send them working prototypes to play with. Suddenly they’ll be hip to the notion you’re sending them working software to play with that is representative of what they’ll actually be using… and that’s a pretty accurate assumption on their part. Their shaping of it also ensures you’re never wrong because you’re basically doing what they tell you to do. Obviously, famous last words for a programmer. Either way, if your the IA/ID or not, you can also use this opportunity to suggest ideas, again giving yourself an opportunity at least appear intelligent.

    If there is a client phone call/meeting, and you have the opportunity to attend, do so. If it is appropriate, start a dialogue to challenge your assumptions about their comments to the recent builds you sent them. Engage with them (and/or sales) in the process.

    Use a phone, not email or IM

    If you’re unsure about something, and you have access to sales, go talk to them in person. Make sure you brushed & flossed first, obviously. If they are unavailable, send them an email. If they are remote, call them, and then only email if they aren’t around and don’t return phone calls. In person dialogue is ideal, whereas phone voice dialogue is 2nd best. Email and IM are not the best form of communication, and communication is the most important thing in a software project. Use the best kind you can to ensure success.

    Caveats and Gotchas

    There are some caveats and gotchas. The more time your team is writing tracer bullets, the less time they are moving forward with traditional visible results. The Agile crew would argue that it is better to spend 4 hours on 2 ideas, allowing the client to pick one they like as opposed to spending 1 week on requirements and then 2 weeks on development for animplementation the client won’t like, which then ends up being another 2 weeks to code to the new idea. Even 2 weeks of bouncing ideas with near production code is better than 2 weeks of “coding off a spec”… well, unless you’re doing government work. It’s hard for some to see the value in writing code that has fake data, and an ever changing interface, seeing the same things in different ways without seeing in their eyes tangible progress on milestones. My retort is they can’t prove their milestones are accurate without the client having some form of involvement in confirming those milestones were met without allowing the client to play with a build that shows that milestone in action.

    Regardless, it’s hard to argue with a Subversion log that says “everything under the View’s folder has changed a lot the last week, but everything in the Cairngorm business, command, and events folder has not… what exactly HAVE you accomplished this week? Can you name one requested feature you’ve completed?”. Valid question, and one that management & sales need to manage; IA/ID & developers can help, but ultimately they aren’t accountable for resource management. Look at it this way: You’ll either be re-coding this at beginning more quickly with less stress using a series of tracer bullets as opposed to slowly at the end with less malleable code under more stress. Use that fact to empower sales. Take the initiative.

    If you don’t have leadership approval, it won’t work. If your manager looks at you funny when you send a “half finished application” the client, you’re already in deep trouble.

    If the client doesn’t care, you’ll really need to leverage your sales rapport. You’ll need to educate the client how software works, and that is extremely hard… but fun. If you don’t, they’ll just expect it to be “done and finished by X date”. That’s not how things work in the real world and they need to realize no matter how much money they spend, they can’t change that. It’s in their best interest to get a good feeling with the software early because it’s easier to change early, harder to change later. If you get those feelings early on, most changes later won’t be so drastic as completely changing workflows.

    Regarding MXML, I’m a big fan of writing my components in all ActionScript. That way, I can re-use them since I have lower level control and can make them really flexible. Again, Flex Builder won’t render these unless you convert them to a SWC (via a Flex Library project for example), so save the uber-OOP for later. If you stick with pure MXML, the tool will work well, and you won’t be fighting it to adopt your best practices. If you have a lot of members on your team, this is also something you can throw at other developers to handle, even junior ones. They can cut their teeth on making a reusable component while you continually define the app via multiple iterations.

    A couple notes on branches and prototypes. First, I’m not a big fan of using branches for one Flex Dev to make some design iterations while the rest of the team “moves forward”. The Flex Dev(s) doing the design iterations should be in the real code. If the rest of the team has qualms with this, you’ll need to setup an easier way for them to test, whether by writing formal/informal unit testing for them on GUI & non-GUI code. For example, one of the benefits of Cairngorm is that it allows multiple developers to work in tandem. One strategy is to have multiple developers handling all Events, Commands, Factory, ValueObject, and Business Delegate code. This leave the Views in the hands of whatever developer(s) handling building the tracer bullets to show sales/the client. The rest of the team can either use the latest build in source control to throw data at and see what happens, and just comment out the actual Cairngorm Event dispatching when they check the code in, but I’ve found it’s easier to just make informal test cases; MXML applications that test your whole Cairngorm use case setup. A la, you build a simple View with a GUI control data bound to the Model, dispatch an event, and see if it works.

    Regarding prototypes, for larger projects I think these are more the than justifiable. Throw away code is quicker to write than tracer bullets, and it’s always good to play with some code ideas before committing more rigorous practices to it before you know the idea will actually fly (strong-typing, encapsulation, etc.). There comes a point though where you should start leveraging the code you are writing in a good base, and really put the code to the test in early builds to see if she holds up.

    Finally, being intimately familiar with Flex Builder helps. I think I’m pretty adept at it, and I’d say that significantly contributes to my ability to quickly modify code without making it spaghetti. My experiences in Director and Flash have contributed to my ability to fake a lot of interactions for the sake of communicating a point. Finally, using OOP, encapsulation, and strongly-typed code to get the tool to help you find errors are all ways to write flexible code. While the temptation is to not even use strong-typing, and use a procedural approach, you’ll spend too much time trying different ideas because you can’t share code easily. Remember, it’s ok to do this stuff on paper or your favorite UML tool first. I just use paper, personally and plaster comps on walls in front of my desk. Now, that experience doesn’t just happen over night. Regardless, I was responding to bi-weekly changes on software projects at my first job of which I didn’t know OOP or how to write classes, nor did I know what design patterns were. I didn’t even know how to return a value from a function (I just modified global values instead). Yet, I found a way, so you can too.

    Conclusions

    Iterative development through speedy coding with Flex Builder. Following the tips above, you can hopefully build your Flex apps a little faster via Tracer Bullets so you can play with some workflow / use case / design ideas and throw them at the client. What they throw back you can then start coding for real on… and then toss that back… rinse, repeat.