Blog

  • Your Mom is null throws Exception OT OT OT … or Learning Exception Handling in ActionScript

    After coding AS3 for about 2 years now, I’ve come to 1 conclusion: I’m sick and tired of testing for null. It seems to be the most common if then statement I write in all of my code. I’ve been doing some pure ActionScript work in the past few months, and I have to so say, the more ActionScript only, as opposed to Flex projects using MXML, code I write has more of these checks. It’s nice how MXML handles all the deferred instantiation stuff for you. I certainly have more appreciation for it. Same with Flash CS3 and automatically declaring stage instances.

    The second reason, however, is exceptions. I’ve never had to use exceptions until now. Half the reason is 90% of all exceptions in Flex are bugs that you can fix in your code. When doing API work, it’s the opposite. I cannot control what gets passed into my code when I plug libraries into some other project. I have the benefit of drinking my own kool-aid; we’re using the very API’s we create. There came a point last week where I realized that some of the exceptions weren’t my fault. Meaning, I could go to a court of law, represent myself, and still win with utter confidence. When developers use an API, you cannot control what they put into it. While you can expose some strongly typed public methods, and hope for the best, but ultimately they’re going to pass something in there that is null, NaN, or just plain wrong.

    For debugging, it’s easy; you can use default values when you don’t have time to correct the one who is using the API if you are coding both yourself. You can’t do that, though, in production. When creating video players for work, if I have 2 million customers having SWF’s on their desktop trying to hit our internal development server that cannot be reached without VPN… that’s a bad thing.

    Running into that scenario, I started trying to handle some of the exceptions myself. I started to get some deeply nested try/catch blocks. The code started to look really nasty (maybe ’cause I’m not used to it). However, I started feeling really confident that if something didn’t work, I can could capture it in one place, and create an error screen for it. After awhile, this spiraled out of control. Suddenly, I was catching just about every method. In short, it’s bs; I shouldn’t have to code like that. Clearly I was in uncharted territory that the C++ and Java crowd had already figured out.

    Whilst the bird was cooking, I went digging on Google and found 2 good articles (Best Practices for Exception Handling, Exceptions in Java: Nothing Exceptional About Them). I told her majesty I wouldn’t work over the holidays; I don’t count learning exception handling as working. The one on Sun’s site I didn’t agree with. Furthermore, while the articles are years old, and appear to disquiet controversy, it sounds like the same arguments Flash Developers have of code on frames vs. no code on frames. Both are valid, 1 is a purist angle, the other a pragmatic angle. Doing my best with just 3 hours worth of research, it seems that Java has checked and unchecked exceptions; in the Flash Player world meaning those that show the debugger popup window in the debug player, and those that do not. I’ve yet to see an exception not show a debug window. I had 1 nestled deeply in a View not do it once, but I think that was a bug in the beta Flex 3 bits I’m using. So… it doesn’t sound like ActionScript has an unchecked exception equivalent.

    That said, if you read Sun’s article explaining the reasoning behind unchecked exceptions, they justify it by saying there are just some errors you either can’t reasonably recover from, and there are too many exceptions to possibly catch. If you did, you’re code would become too verbose and un-readable.

    I call busllshit. First off, YOU MUST recover. If you’re a GUI developer like me, you know that you can’t show user’s a cryptic error screen, or worse, nothing. Heck, if you’ve ever used Windows and got some useless error screen with no information on how to proceed, all it did was make you frustrated with no clue on how to solve your problem… nor even a clue as to what the problem even is. Unfortunately, this is a problem in the Flash Player as well; there is no way to catch all exceptions assuming you put a big-ole try catch on _root for example. Even though exceptions can act like events for asynchronous exceptions (aka, Error’s that have an Event equivalent are dispatched when something goes wrong, and you ‘catch’ them like you do events via addEventLsitener ). You can’t do that, but that’s what a lot of us want for Enterprise apps, or those apps that CANNOT have errors thrown under any circumstance in production code. I’d still argue, however, that most of the relevant ones you can catch and handle. There is a caveat to this I’ll mention later.

    Secondly, after reading the 2 other articles, you are not pre-disposed to write bad code proportional to the amount of exceptions thrown. This is a fallacy Java’s designers apparently thought would happen… maybe they didn’t want to have their uber-sexy OOP language look like Eiffel, no clue. Bottom line is, there are good ways to throw and handle exceptions in Java, C++, and ActionScript.

    After reading the articles, one mentioned the anti-pattern of deeply nested try / catch blocks. I’d only be doing exception handling for 2 days, and already I used an anti-pattern… sweet, I suck! In doing so, I clearly recognize the key point in one of the articles; exceptions can break encapsulation. The consumer of the API had to know too much about the API to use it; meaning, it had to know what could go wrong with it and handle it. Shouldn’t an API handle it’s own problems or at least lessen the amount of code I have to write? Isn’t that the point of an API? When I started seeing my code checking for IOError’s on URLLoader, which my code shouldn’t even know a URLLoader is being used, I clearly saw the break in encapsulation. It’s a bad feeling to not know if you are doing something correctly. It’s great, however, to know you are clearly doing something utterly wrong. That means there is a RIGHT way to do it. Google search FTW!

    Java has this thing called throws; it’s a keyword that goes on the end of a function in Java, and forces the method that calls it to use a try catch block just in case the method does throw an error. It’s nice because it’s a compiler thing, so the code won’t even compile unless you use the method correctly. This is problematic in ActionScript for 2 reasons. First, ActionScript doesn’t block so you can’t do a try / catch on an asynchronous method. Secondly, there is no “throws” equivalent for events; since Error’s are treated as events and dispatched the same way, you cannot force someone to use an addEventListener in ActionScript. Even if you could, you cannot control how they do so. For example, if you used a weak listener to an addEventListener, and there were no hard references to it, so Garbage Collection ate it, the exception wouldn’t be “caught” by an event listener. Technically you made the compiler happy, but you failed to catch said exception/event.

    The point here is in Java this is part of the language, the contract that goes along with strong-typing. While interfaces are a programming by contract methodology, so to are throws in Java. It seems to me this is not a strong point of ActionScript (at least the parts ofECMA 4 it’s implanted; haven’t read where ECMA 4 is going), nor are there any best practices yet since the API creation field for ActionScript has just now started on a major up-swing (don’t believe Zoho, they’re full of it, there are a lot of great AS3 libraries. Do a google search).

    To Sun’s credit, in reading the 2 articles, I didn’t realize one particular scenario, and that is if your API is put into a GUI you don’t have control over. It’s really easy for me to think, “Sure, if there is an error, I’ll just have my designer create an error screen for it, or have some Information Architect / Interaction Designer document which exceptions do what in the interface”. That’s all well and good if you are the one both creating and consuming the API. For some of our customers, that is a set of glorious, and wrong, assumptions. First off, they shouldn’t have to know about our API too much to use it. For all the crap I give f’ing DoubleClick , their API is brain-dead simple to use. They still suck that they don’t support AS3, though. Second, I cannot control customers’ GUI; if they choose not to show an error screen because something didn’t load properly, who’s fault is that… mine or theirs? It’s mine if I didn’t provide an easy, simplified way of letting them know when something went wrong. Only then is it theirs. Third, error handling is yet ANOTHER thing to do. Thus, it takes time. A lot of Flash work sometimes is under insane deadlines; just because I have reasonable deadlines with reasonable management and competent developers does not mean that our customers will be as lucky. I need to work extra hard to make sure I make their job as easy as possible. Aka, a good API.

    In short, what I gleaned is:

    1. Don’t ignore exceptions. Find out why your code is breaking and fix it. For those situations which you can’t control, handle it, clean up your mess, and dispatch/throw an error.
    2. Don’t over architect your Error’s. Some internal error’s are perfectly named; use them instead of your own. The RangeError is a good example. If you try to access item 10 of an array that only has 9 items, you don’t need to abstract that further, nor shield an API user from it. It’s a simple error that comes from using array’s.
    3. Going along with point #1, if you have a ton of errors that could potentially happen, consolidate them so users of your API only get 1 error (or is few as possible). You do this by extending Error and then throwing / dispatching it. If they really want to know the root cause, store the original error as a class member.

    Again, if you are creating a Flex app, you probably don’t have to worry about this too much. I’d argue most exceptions are something you did, in your code. A lot of us Flash Developers have the perception of exceptions as being “errors in your code”. Our attitude typically is, “If there is a bug in your code… fix it.” This perception breaks down when you start creating API’s for others that you cannot control how they use it. That, or just the user’s internet connection goes down and an IOError is thrown. You can’t fix the interwebs connection using Flash.

    I’m sure how to resolve Joel’s angle. While I wasn’t much of a coder back then, handling “error codes” in Director’s Multiuser Server was a royal pain in the neck, so not sure how to code to what he’s suggesting. Painting by numbers is fun… coding by them is not.

  • Flash & Flex Integration Gotcha: Automatically Declare Stage Instances

    I’ve gotten a lot of emails asking about some of my older Flash & Flex integration examples not working. Hopefully this article will describe the same error everyone is getting.

    ActionScript 3 is strict. However, Flash CS3 helps Flash developers with a feature that automatically generates code during compilation. Meaning, if you have a MovieClip on the stage called “my_anime”, you won’t have to declare a variable like so:

    public var my_anime:MovieClip;

    Flash CS3 will automatically write that in the code for you.

    If you didn’t have that code, you’ll get a runtime exception. That’s because the timeline is effectively going:

    yourMovieClipInstance.my_anime = new MovieClip();
    yourMovieClipInstance.addChild(yourMovieClipInstance.my_anime);

    Since yourMovieClipInstance’s class doesn’t have a property called “my_anime”, it’ll blow up. For a Flex Developer, this makes sense. Everything exists, and you merely addChild/removeChild or toggle the visible property. In Flash, things may not exist till frame 10. For some animations that have a ton of child MovieClips that you need to talk to, this can be a lot to remember. So, the ADSI feature is nice in that Flash worries about it for you.

    Flex has no such feature.  When you bring in Flash content, you’ll get an exception, and you can’t debug it easily because it was the MovieClip’s timeline who caused the error. When you go to debug, you’ll get the 1 line exception “ReferenceError: Error #1056: Cannot create property” in the call stack, and nothing more… and you’re left wondering, who the heck is creating this thing?

    While I agree why Adobe put the ADSI feature in Flash CS3, it works against you when you create content for Flex. Take the pain of writing out all of your MovieClip’s as class member properties, and uncheck ADSI via:

    1. File > Publish Settings
    2. Flash tab
    3. Settings button
    4. un-check “Automatically declare stage instances”

    Good to go funky coma-deena.

    Here’s the settings screen:

    Settings Screen

    Here you can see a new animation starts on frame 25. Therefore, if there is no class variable called “box”, you’ll get a runtime exception. In Flash CS3, however, you won’t if you have ADSI checked.

    Timeline Animation Example

    Here, you can see I define the box on line 8; this prevents a runtime exception when you embed the SWF in Flex.

    Class Example

  • Converting AS3 to AS2 and Surviving AS2 in General

    If you are in a hurry, skip to Gotchas.

    Introduction

    There are a variety of reasons to still use AS2. Some of the more realistic are:

    1. Supporting legacy content
    2. Awaiting a larger corporation to sign off on AS3 development
    3. Having to work with a client-side API written in AS2 by a third party

    In my case, I found out #3 after I was well over 3 weeks into development of an AS3 solution. As more and more traditional programmers learn ActionScript 3, whether from Flex development, or from curiosity about how one would code JavaScript in newer browsers from Mozilla via the Tamarin engine, you may also be put in a position to maintain or modify some AS2 content, typically written in Flash.

    Even with “as3” and “es” set to false when using the mxmlc compiler, you still aren’t capable of using Flex Builder 2 or 3 as a serious solution to doing ActionScript 2 development. Furthermore, Flash the IDE (CS3 in this case) isn’t a serious development environment either. While Flash CS3 did add some minor code editing features, it’s pretty clear form that release that Adobe has no intention of improving AS2 development in Flash.

    If you are maintaining a sizable code base, or simply converting it, whether to support a 3rd party API or merely to keep your sanity, having a good tool and some advice on how to quickly get past the gotchas can really make a difference.

    Tools

    AS2 really jump started the open source industry for Flash. There are a plethora of options out there. Unfortunately, when this industry was ramping up, I jumped ship to Flex. You can investigate yourself over at OSFlash.org. I have no clue what is good for Mac, however…

    …for PC, I recommend FlashDevelop. No, not FDT (Flash Develop Tool), just FD. If you see a forum, you know you’ve reached the right place. That’s correct, it doesn’t even have a proper web page. I use Google to actually find the download page on their site for the software ( flashdevelop download site:flashdevelop.org ) It’s just that good. Steven Sacks took me through a Breezo of this program almost a year and a half ago. It’s written in .NET (but suggests Java 1.6???), hence, I lug both my Mac AND my 14.5 lb PC laptop to work JUST so I can use that one piece of software. That’s right, a $2,600 former gaming laptop just to use an a piece of open source software. I say again, it’s just that good. Speaking of Alienware, they like DoubleClick, can go diaf together. Anyway, imagine Flex Builder, only for AS2. Code hinting, code completion, etc. Yes, for your own classes, not just Adobe’s.

    I’ve converted to mostly Mac for full time Flex & Flash Development. However, I own a copy of CrossOver to use just one piece of software: BeyondCompare. This works just as well for AS2 as it does for AS3. It’s code diffing software, and I use it to sync my local copy with Subversion’s.

    While you technically only need Flash MX 2004, Flash 8 runs more predictably, and Flash CS3 has both 8’s stability, with some minor compiler & code editing changes that make it bearable to be in the 5 minutes of your day you just have to use it instead of FlashDevelop. If you can get a copy, do so. Keep in mind, if you wish to use Flash Player 8’s new Garbage Collector and filters, you’ll need Flash 8, and if you wish to compile to Flash Player 9 for use of full screen functionality, you’ll need Flash CS3.

    If you are maintaining a Flex 1.5 code base, my heart goes out to you. In a box. Stabbed with a rusty knife. Send the box to your boss, maybe he’ll fire you, and you won’t have to maintain a Flex 1.5 code base.

    Gotchas

    This assumes pure AS, and doesn’t take into account components.

    If you are converting from AS3 to AS2, do a find and replace on the following:

    • void to Void
    • int and uint to Number
    • const to var
    • :* to :Object
    • protected to private
    • remove all “override”
    • public class to class
    • :Shape to :MovieClip
    • someMovieClip.graphics to someMovieClip
    • remove :void from constructors since in AS2 they cannot return a value

    I haven’t found an easy way to manage converting your package path back to prefixing on the class name, so have been doing this as well as deleting unsupported imports by hand.

    If you use the Graphics.drawRect, you’ll have to write a wrapper function that emulates what it does. There is some good AS1 code on Adobe’s site to write a quick Utility class for drawing.

    Your creation methods and addChild/removeChild is really where a lot of your work is. Converting them to attachMovie factory method is correct, however, making a method that checks for types is a little better to at least ensure your variable casting is good to go. Know, however, that MTASC in FlashDevelop, and the Flash IDE expect different things in different places. Casting in AS2 doesn’t always work, nor is it always consistent like AS3. You don’t have the as keyword, and as such, you can only cast to things that don’t have constructors that do magical things, like Array that actually makes an array vs. casting to an Array.

    If you want addChild/removeChild features, use _visible = false, _visible = true instead.

    Watch your default values with magic numbers. Changing your scaleX to _xscale is not enough; remember, it’s:

    AS3: scaleX = 1
    AS2: _xscale = 100

    Big difference. Same goes for alpha values.

    While try / catch blocks are supported, they do something uncool in my opinion. In Flash Player 9 using AS3, you get an exception window in the debug player. In AS2, you do not. You’re code magically stops and you have no idea where. All exceptions are usually automatically caught and handled internally in AS2 and below, so if you check a null value, the next line of code is still run, and your app goes on it’s merry, albeit wrong state of mind, way. This made bug hunting in AS3 a lot easier than in AS2. It also made try catches actually useful vs. something to make the Java devs feel comfortable in ActionScript. However, try catch blocks in Flash Player 8 and below actually abort ALL code in the stack; this can be viewed as a good or bad thing. Good because if nothing happens, you can blame it on a try catch block. Bad in that it can be really hard to see the ramifications of the bad code. This makes it really hard to debug other parts of your application using breakpoints in the Flash IDE because if the try catch aborts a stack that would of caused your other code to run, you’ll never get there.

    Interfaces do not work very well in ActionScript 2. Furthermore, you cannot have getter / setters in an AS2 interface. While extending works, the implementations can be really tricky. If you spend more than hour fighting your code to accept the interface, go with convention, and just trash the interface… or use a psuedo base class. If you can’t use a base class, use a mixin (a class/function that adds methods to a Class’s prototype at runtime or simply just decorates an instance).

    A note about using mixin methods; those too also don’t always work with interfaces. For example, this:

    function removeEventListener(target:String, listener:Object):Void;

    In your interface doesn’t think this is a valid implementation:

    public var removeEventListener:Function;

    While it’s technically correct, what it doesn’t know is that at runtime, with the mixin, it WILL be. There is where tools & languages haven’t matured enough to support prototype classes. Therefore, just re-define the method the correct way to match the signature, but don’t have it do anything. Yes, it uses slightly more RAM and resources, but oh well.

    Don’t expect your initialization order to be correct in static methods. Meaning, if ClassB uses ClassA, one would expect the compiler to see that, and initialize ClassA first, and then ClassB. This was a problem that surfaced in Flash 5, was fixed via hardcoding the initialization order in Flash 6, and eventually done by the compiler in Flash 7. It doesn’t, however, work that great at least in some static methods that do class constructing things while the application is initialized. You may be able to hack it by writing your own class initialization stuff inside a MovieClip with an #initclip 0, but in my quick test, like zee goggles, it do nothing.

    If you don’t know what a Delegate is, don’t worry about it. Just change this:

    something.addEventListener("eventName", functionHandler);

    to this:

    something.addEventListener("eventName", mx.utils.Delegate.create(this, functionHandler));

    Keep in mind the MTASC compiler uses a stricter set of rules (yes, even with strict mode turned off) and doesn’t work natively with the mx components unless you explicitly tell it to ignore them. FlashDevelop has GUI options for this vs. writing command line compiler options. The one thing that can cause issues is intrinsic files; files used to represent classes native to the Flash Player, but still needed for compile time checking. This are AS2 classes that have method & property signatures, but they don’t actually do anything. This can cause problems when they differ.

    For example, NetConnection has a method called connect. Depending on what documentation you read, it can return different values. Flash Communication Server (now known as Flash Media Server) says it returns nothing; newer docs say Void, whereas MX 2004 says Boolean. The Flash AS2 compiler assumes Boolean as well, but MTASC’s intrinsic says Void. You’ll get this neat error message in FlashDevelop saying “Void should be Boolean”, yet it points the error being in the intrinsic. So, you can either edit the intrinsic, or just add that one particular file to an exclude list, and move on knowing it’ll compile just fine in Flash.

    That’s all the major stuff. Good luck!

  • DoubleClick and ActionScript 3?

    Has any used DoubleClick’s Dart/In-Stream, etc. solutions with ActionScript 3?

    They currently only support ActionScript 2, 1, and 0 (code on frames). They do not support going directly to their web services. We entertained reverse engineering their API, but the problem with that is being held accountable for the video metrics they handle via FLVPlayback/NetStream and having to emulate those perfectly. This is also why an AS2 / AS3 LocalConnection option won’t work out well because you have basically write a Facade NetStream, and pray you not only match every method, but also dispatch every event.

    Naturally I’m not looking forward to using AS2 for a number of reasons. AS3 would of allowed us to use runtime skinning, thus reducing the amount of code we need maintain for a variety of clients; skin.swf’s vs. unique video players that increase weekly resulting in a large maintenance cost.

    I’m still investigating 3rd parties that usually act as the middle men to DoubleClick, lowering the amount of bling you have to front to even get a return phone call. Apparently some of these firms have API’s of their own that abstract DoubleClick since they wrap their own reporting and billing data around it.

    Anyone???