Blog

  • Loading Random SWFs in a Strongly Typed Way

    In a hurry? Skip to the code.

    ActionScript 3 has given us true strong-typing; both compile time and runtime. This has many benefits from helping ensure code works once you actually compile as well as helping you debug runtime errors. The problem with perfect systems however is when you put in some chaos. The old adage, “garbage in, garbage out” holds true here. There are basically 2 ways to get weird stuff in Flash Player. You either load in external data and parse it, or you load in an external SWF.

    The former is a little easier to deal with. Using E4X, if some XML node doesn’t exist, your code doesn’t throw exceptions. You can test against undefined, and set default values that match your ValueObjects (strongly typed classes that represent your data). In short, you can correctly write an XML parser that shields your app from bad data. Granted, his job is the most important as he’s the guardian against all loose wrenches in the gears. I’d say the majority of the bugs in the software I write in AS3 comes from a Factory letting bad or missing data through without either compensating with default values, or dispatching an appropriate error. In the end, though, if you do it right, you’re good.

    External SWF’s, on the other hand aren’t really parsed. There are some bad asses doing some weird things with SWF’s, like loading them in for asset use only (since even Images are classes now that can be ripped out of externally loaded SWF’s, aka WinAMP skinning) or just Flash native data transfer objects like Aral does with SWX. For the most part, most use cases that call for loading in an external SWF are NOT positive beyond the 2 above. Some common use cases not including the above are:

    • loading in Flash Player 8, or below content
    • loading in Flash content created in the Flash IDE as opposed to Flex
    • loading in assets too big to compile into main SWF and un-linkable to Flex’ RSL work flow (audio, video)
    • 3rd party PRE-generated created SWF’s (even if AS3, still could use different component set)

    This entry will target #2 and #3. For #1, here’s some morphine. For #4, good luck in the politic-infused blame game meetings.

    Flash is damn good at creating creative content. Whether this is created in-house or outsourced to a 3rd party design firm, you can have this content be in Flash Player 9, AS3. While this sounds positive, it just sucks you cannot easily make this a part of your work flow. There are a few ways I’ve talked about in the past using the Flex Component Kit for Flash, which is now part of Flex 3, or simply writing wrapper classes. The Flex Component Kit is really great if you know ahead of time the scope of what the Flash will be, or it won’t be in flux. The same goes for the wrapper classes with those who are in more formalized programming environments.

    However, sometimes you just get this problem that just defies all conventional ways of solving it. For example, a not-too-small widget was created in Flash CS3 using the new components. It may not easily portable to the Flex components in a reasonable time frame. What do you do? Attempt to get the Flash components to compile, with assets in Flex? I’ve tried this myself and wasted a bunch of time on it. I’m sure it’s possible, but I’m past trying, instead getting work done.

    Real world scenario; DoubleClick’s In-Stream for AS3. Apparently you can get the SWC to work in Flex… we couldn’t. Even if we could, you can can’t test the S.O.B. locally, needs a webserver… So, you have no choice but to use Flash in this scenario.

    In those situations, all you can do is load it in at runtime. The silver lining? Both are AS3. AS3 SWF’s can talk to each other. Your Flex SWF can call methods on the loaded Flash SWF. However, to call methods, the Flex SWF must “know” about those methods; hence being strongly-typed. You’d then have to share the same class between SWF’s. While this wouldn’t be too bad, Flash CS3 broke exclude.xml, the ability to compile a SWF, but excluding certain classes from it. You did this so you could prevent compiling the same class into multiple child SWF’s that you knew would have the same class waiting for them in the parent.

    Sanders commented on my past blog entry about this that there is apparently a way to get it to work. I haven’t read into it, but using intrinsics (namespace internal) seems a valid solution. Using JSFL, it’s also tons easier to create code generating and others tools for Flash than it is for Flex and ANT. Then again, I haven’t tried Europa’s (Eclipse 3.2) JavaScript API yet… me? Digressing? No way…

    Dirk originally came up with the idea of using interfaces when loading Flash content into Flex. At the time, Flex was Flash Player 7 only, and Flash was at Flash Player 8. Flash Player 8 had all the new effect filters; Flex did not. Using interfaces, you could utilize BlurFilter for example via a SWF liaison; file uploading too.

    The reason Interfaces are nice in this scenario is firstly because it’s small; it’s just a tincy class, usually less than 1k (micro-small in bytes when compiled to bytecode). Since you will be adding this interface to 2 or more SWF’s, it helps to lessen the damage. Secondly, it’s strongly typed, even in AS3. You cast things to Interfaces and even test if something implements an interface the same way you test to see if an instance is a class via:

    trace ( cow is IBigPimpin ); // true
    
    trace ( cow is ISpendinGeez ); // true
    
    var rad : IUberYum = cow as IUberYum;

    The steps for loading in a strongly-typed SWF are as follows:

    1. Create an Interface that both Flex and Flash will utilize.
    2. In Flash CS3, have your Document class implement that Interface.
    3. Compile your SWF (aka Test Movie).
    4. In Flex, load in the SWF.
    5. In the Event.COMPLETE handler, cast the result to the interface, and store it as a class member variable.

    Here’s a sample interface that we use at work to handle a loaded Dart.swf. It loads pre-roll videos and ads (animated GIF’s or SWF’s). Notice the events… they give you code hinting in FlexBuilder for loaded SWF’s (Flex 3 only suckaz), woo WOO!

    package com.multicastmedia.doubleclick.core
    
    {
    
            import com.multicastmedia.doubleclick.events.DartEvent;        import flash.events.IEventDispatcher;
    
            [Event(name="gotCompanionAd", type="com.multicastmedia.doubleclick.events.DartEvent")]
    
            [Event(name="prerollDone", type="com.multicastmedia.doubleclick.events.DartEvent")]
    
            [Event(name="error", type="com.multicastmedia.doubleclick.events.DartEvent")]
    
            public interface IAdModule extends IEventDispatcher
    
            {
    
                    function loadPreroll(adx:String,sz:String):void;
    
                    function getCompanionAdURL():String;
    
                    function getCompanionAdClickThrough():String;
    
                    function setVolume(val:Number):void;
    
            }
    
    }

    …yes, I know the DartEvent is compiled into both SWF’s, HOWEVER, it is tincy, and in this case worth it since it’s needed.

    Here’s some psuedo code to load the SWF into Flex:

    // reference to the SWF so you can call methods on it later
    
    var dartSWF:IAdModule;// this can be a SWFLoader in Flex instead, doesn't have to be Loader
    
    var loader:Loader;
    
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
    
    function onComplete ( event : Event )
    
    {
    
            // once loaded, cast t3h SWF as an IAdModule
    
            dartSWF = loader.content as IAdModule;
    
    }

    The caveat to this, which I haven’t tested, is if you load your classes into a different ApplicationDomain. The only person on the planet I know who does this is me, so you don’t have to worry about it.

  • Who Has Time for Unit Tests?

    A couple months ago, I read about dpUInt, yet another unit testing framework for Flex. I got it from reading the docs, it seemed easy to add to an existing or new project, and I’m all gung ho for giving it a try. If it sucks, I know I have both FlexUnit and VisualFlexUnit as back up frameworks.

    Test Driven Development practitioners are very passionate about what they do. They give off this air that my early OOP mentor’s also did, “Once you go TDD, you never go back”. The funny thing about OOP in Flash is how quickly it dies a pathetic little death when a deadline rears its head.

    The amount of sustainable OOP in Flash is proportional to the deadline length. If I have 2 months, classes & framework for the win. If I have 2 days, screw you, on(press) { copyPasteCodeOnObjectsAndInFrames(); } and then show client early ’cause you know they’ll have massive changes.

    Is unit testing like this? When I read Peter Bell’s blog, and other unit testing scenarios, I get the sense that an existing solid software base is used. Templates are modified, run through tests to ensure the new code & design works, and then the code is deployed. This cookie cutter pattern repeats, and can repeat, because the original software is solid, is customizable for a wide variety of common customer needs, and unit tests ensure everything keeps humming along.

    The other sense I get is developers already know what they’re going to write.

    I’ve never been in either scenario. Either I’ve had to build from scratch, re-write from scratch, or build atop of crap because the client heard “re-write” and thus freaked out (thus re-writing from scratch). Even in the best planned waterfall based projects with good IA’s, and somewhat flexible deadlines, it’s always been a process of discovery, modified requirements, and re-factoring/re-coding. This is in partly why I enjoy programming in Flash & Flex. Not only do I get to do that stuff with code, but also with design.

    Therefore, it’s really hard for me to imagine how I could START writing test cases first in my project. The closest I’ve come to writing “tests” is when I create a new FLA to test a component that’s acting weird. Instead of testing the entire project, I’ll just boot up a new FLA in Flash, import the component, create it, throw some fake data at it and see what happens. In this way, I can more quickly find the problem, AND re-use the testing FLA (70% of the FLA’s anyway) at a later date if the component acts up again. This is after the fact, though.

    The same thing in Flex. If I inspect the HTTP traffic through Charles, and see that the webservice is returning everything fine, and debugging doesn’t reveal anything obvious, I’ll set up a test file that instantiates controls in a really simple environment. Instead of a large app, it’s 2 controls that interact with simple fake data. Again, this really helps me isolate problems and more easily find them. It also makes it easier for me to not only test later, but quickly test smaller portions of my code.

    Granted, sometimes I don’t like “going to all that trouble” and keep doing risk debugging; where you swear that in just 1 more compile you’ll find the bug and fix it… yet this is the 4th time you’ve said that and you could of already been well on your way creating a test harness to more quickly and assuredly find and fix the problem…

    Again, though, after the fact.

    Like everything in programming, I’m still reading more sources to get a better idea, it’s just hard to get a good feel for who in the Flex & Flash community is doing unit testing, and how. With the influx of traditional developers in the Flex world, I’m seeing more talk about it, yet not enough case studies with good details on how the work flow actually works from requirements gathering to sitting down and coding. Flash devs’ll try anything, just point us to the right way!

    People would ask me to justify the time it takes to actually use Cairngorm. In their example code, all they really did was neatly wrap 1 line of code setting 1 variable on a single ModelLocator in a Command. I’d respond that either they wait 3 months, and compare the newest Command in SVN with the one they emailed me to get their answer. If that didn’t make any sense, or they just didn’t want to have faith in JXL, I’d instead point them to a lighter weight framework.

    Am I in the same predicament? Are my deadlines, lack of hardcore requirements, and/or inability to easily articulate a base design preventing me from really benefiting from formal unit testing or do I just need to read more?

  • I Will Not Write a Book

    I keep getting emails with offers to write a book, or to help contribute in writing a book. While I’ve entertained the idea of doing a chapter (or 3) on Cairngorm, that’s just what it is, and will always be; an idea that I have no intentions of bringing to fruition.

    From my experience and talking to others in the Flash community, books pay jack both in lump sum payout and royalties. This is compounded with insane amount of time and energy it takes to write a good technical programming book, especially in a hot market right now. I could spend 4 months making shit money on a book that has a shelf life of 1 year with pathetic royalties NOT improving my skill set… or I could spend 4 months making hundreds of dollars an hour writing code improving my skill set.

    Gee, hard decision.

    Not only that, but finding technical editors, good ones who know ActionScript AND have time to proof read your chapters and test your code, is impossible. I know from personal experience, I was a technical editor for 2 books in 2005 and 2006, saw the challenge to get chapters checked even with a good amount of technical editors. I sucked at it, and felt horrible after words. Did I mention I didn’t get paid as a technical editor either? Not that I deserved it. Oh wait, a free book… um… I make that in 10 minutes of coding. Ungrateful bastard, I know. Seriously, who do you know that is good at ActionScript and is NOT busy as hell? Thought so. How do you make them not busy? Offer a higher rate than their next gig or just get lucky that they somehow feel the need to add technical editor to their resume.

    If you are a publisher reading my blog thinking that I’m a decent “candidate” to consider for authoring a book, while I appreciate your consideration, move on. The only book I want to write is only half technical, and have no clue if it would sell.

    …then again, I did get burnt out pretty bad at the beginning of 2007, quit consulting, and played Gears of War on my XBox for 3 months straight unemployed… I don’t recall that positively affecting my skillset although I did meet a lot of cool whacko’s on XBox Live. *ahem*.

    Ok, in that case, if someone can justify why it’s career advisable (…yet another resume bullet point does NOT count), how to get these publishers to front decent bling (aka, I can make $85 to $120 an hour contracting/consulting independently, non-firm associated right now for reference), and how to sell them on my whacky ideas I think would sell, then I might consider it.

    I mean, just because someone wrote a book doesn’t make them impressive to me. I’ve read some really bad Flash and programming books as well as some bad ass ones. There seems to be this benefit that if you write a book, you’re immediately perceived as an expert, even if you really aren’t, which is complete bs. Then again, there is something insanely pimp and philanthropic, and therefore self-fullfilling, about pouring your heart, soul, and knowledge into a writ for the pure goal of helping your fellows. Seriously, on the fence big time. Guy Watson and I think alike on this (at least he and did 3 years ago :: shrugs :: ).

    I’d argue spending one’s time coding, working on open source, and blogging, even if aforementioned tasks are done independently, are worth booku’s more to your personal career in both time, less stress, and money, both short and long term. Am I wrong? Naive?

  • Rails is Ghetto

    Rails is Ghetto: Zed, a developer, rants on his way out of the Ruby on Rails community. If you can navigate through the vitrol, there are some great 1 liners in there about software development & consulting. Not work safe.

    Via SixSigns.