Category: Flex

  • 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

  • I have a hard time writing slow ActionScript 3

    I have a problem going backwards. When I learned attachMovie in Flash 5, that function was the death knell for my Director career. “Create something from nothing!?!?” :: queue Quake sound :: “GODLIKE!!! (nsfw)“.

    In Director, everything you wanted to be on a depth had to have had something there originally, put there on the “score” (Director’s timeline). If you didn’t do this at author-time, you couldn’t swap things out on that depth. The attachMovie function in Flash was great because this didn’t matter; I had thousands of depths to play with; the sky was the limit!

    I later learned the sky on _root had a limit; it was called the Settings Panel. Lakitu wouldn’t even go near that elevation. It didn’t matter though; creating new MovieClip’s allowed millions of depths that designers & coders never used; it was wonderful.

    To be fair, you could abstract this stuff in Director. The crew over at Director-Online had at least 2 sprite engines that emulated what Flash did, with extra features. Furthermore, I couldn’t really appreciate this stuff back then anyway; I couldn’t even return values from functions. I just had functions set global variables. Class? Que? n00b.

    I tried going back after I learned some things, but I just couldn’t do it. Flash offered too much. It was soo fast. So much more effective. ActionScript just seemed more organized than Lingo.

    After getting over my frustration at AS1, I learned that I could create re-usable stuff. While I loved to re-invent the wheel ALL THE FRIKIN’ TIME, it did get tiring after awhile, especially when my 4th generation Scrollbar still lacked track clicking and scroll buttons. Creating re-usable tools was hot.

    After getting over my furious frustration with AS2, and learning enough design patterns to pretend like I knew what I was doing, I slowly developed a loathing for AS1. I then had a hatred for anything not AS1; aka, code puked on frames.

    I remember seeing a lot of creative things done with prototype in ActionScript 1, however, and even some still in AS2. So, I tried to go back, and experiment. I always ended up getting bit in the arse in the end.

    When AS3 came out, the early version, it actually wasn’t that different (for me) from AS2. AddChild vs. createNewMovieClip, aka the new DisplayList was pretty easy. Protected vs. private, and other namespace features made sense pretty quickly too. The only hard thing was learning the immensely large new API. It’s one thing to remember that a CheckBox emits both a click AND a change event in the Flex SDK, and you need to care about the latter… it’s another to remember that navigateToURL is in the flash.utils.* package. Even the built-in stuff is immensely large.

    What is interesting, though, is that I never developed a hatred for AS2. Because of the complete and utter lack of communication between the 2 AVM’s, combined with Flex’ slow rise to power meant a lot of parallel AS2 and AS3 work. If you asked me if I wanted to do an AS2 or AS3 project, I’d probably respond AS3, unless your deadline was a week or less.

    …and that’s my point. Writing AS3 is slow. It’s finally reached a maturity as a programming language; a real language, not a “scripting language” because it now officially compiles to machine code on 3 differentchip sets. As a real language, it has all the features (most, hehe… private constructor what, abstract classes who?) a traditional programmer would expect from a programming language.

    My boss, a professional Java Developer who now does a lot of PHP (and I’m sure has a larger illustrious career I don’t know about yet), said that a strongly-typed language should be making me faster, not slower.

    In shock and anger, I pulled my phone from my pocket, called up “Bullshit”, and requested he leap upon my bosses’ head.

    There is a reason I click the “Flash” icon on my task bar, do File > New, hit F9, and test a new String parsing algorithm there in AS3 instead of going the ActionScript project route in Flex Builder… or even “new ActionScript File” and making it launching it as an Application. Flash is faster. Sure, once you get rolling, you can have some good test bed code combined with test cases even run by ANT in Flex. I’d still argue the instant gratification in Flash beats Flex.

    …but it doesn’t stop there. I mean, after hearing about things such as “int promotion” and “compiler optimizations based on clear, strongly-typed variables”, AS3 can get out of control. Parsing a pipe (|) delimited string, properties separated by commas (,), with name value pairs separated by equal signs (=) has gone from 15 lines in pre AS1 to 40 in AS3 if you ensure every parsed variable is strongly typed. For an algorithm that’s only run one time very rarely, AS3 doesn’t really benefit here.

    Fine? Then why not NOT strongly type so much? Only strongly-type to ensure you don’t get any type casting exceptions, and move on with life?

    …because… I … can’t. It’s hard to stop. I’ve been trained by the fear of the software engineer army to strongly-type everything. To ensure the compiler has a crystal clear understanding of everything, and that my code will run at moch-10. I can have faith that the old AVM will never even need gas, because the key in the ignition for it will never be turned. All the code I write now ensures everything is typed, and all namespaces are correct.

    I’ve tried abandoning namespaces and using *, Object, and even just abandoning type-casting in general for quick tests or prototypes. It’s just as time goes on, I find the code I add to those things starts getting more AS3 like.

    Bottom line, it’s really really hard to break the habit. Every time I go back to AS2 for some random project, I’m reminded how damn fast it is to create things in it. Half the exceptions I get in AS3 I really don’t care about, and don’t need to know about; they don’t impact the project from working if they are small in scope. A lot of my data is either primitives or simply arrays.

    For smaller projects, AS2 is still the bomb. For smaller algorithms, less strong-typing just results in less, more readable code.

    I can see why professional Ruby, JavaScript, and Python developers still exist. I don’t care what anyone says, loosely typed scripting languages still kick ass. While I wish their engines weren’t so damn slow for larger projects, lately, I’ve just been finding that for a lot of smaller scoped projects or areas, I’m glad I have the loosely typed option.

    While I fully believe the majority of the industry will use C# for Silverlight 1.1 going forward, MAN was it refreshing to write it in JavaScript for 1.0. Taking a break from AS3’s strict ways was great. SmartFoxServer has an option similar to later builds of Red5. You can write in the standard Java for performance reasons OR in your scripting language of choice (JavaScript, Python, etc). For a lot of work, scripting languages are good enough, and since they are good enough, you can write less code, faster to get the same result. That last part is debatable, but not by me. After having a career in both, to me they both clearly have their place.

    …what I can’t figure out is how to drop the “good habits” that AS3 teaches you to go back to fast and furious ways of scripting languages.

  • Flex GUI WYSIWYG Creator Prototype

    Screen cast and source at the bottom.


    Preface

    John Grden created something like this in the past called FLEXible. Basically, you use Flex as a drag and drop interface to create GUI’s. The GUI’s are represented as XML, and this XML is used in another context. FlexBuilder creates and renders MXML as well as ActionScript. Web browsers render HTML, and a variety of tools from Notepad and Dreamweaver can create HTML.

    The reason to use a WYSIWYG editor for layout is that you get more visual control when laying out interfaces. Sure, you can edit an x attribute on an XML tag for pixel precision, but if you want to see the entire interface, a WYSIWYG is the way to go. You can make a visual change, and see how your design is affected. A lot of early Flash Development was layout of the interface first, code second.

    Another use of WYSIWYG editors is for Content Management Systems. In the case of intranets, some have small sections where you can enter custom text, whether normal or HTML, that show up in approved sections of the company website. More advanced ones like WordPress blogging software has a plethora of controls for writing a blog entry. Many buttons will automatically write the appropriate HTML for you. This saves massive amount of time, and allows you to focus on your blog and, and less time on how your blog entry is made.

    We have wants at work for a variety of visual CMS WYSIWYG editors. For customers who request minor graphical and layout changes to their products they purchase from us, it is much quicker to simply re-position a GUI element via a WYSIWYG editor, confirm visually in real-time that is what they want, and save these settings to the profile. This, as opposed to changing some text markup or a value in a MySQL table, and going through the management chain through phone calls and email to answer the question, “I made the change; were they ok with it?”.

    While both actions can take about the same amount of time, using a simple WYSIWYG editor doesn’t require a degree in computer science. Nor does using WordPress ‘ text editor. Easy to use interfaces that generate the necessary code. Whether they are used by users, or client managers doesn’t matter; what matters is that developers are developing instead of spending their valuable (read costly) time on making extremely minor graphical changes to things that anyone could do that had an Internet connection, a web browser, and login credentials.

    I’m all about reducing overhead costs.

    The OTHER Drag and Drop in Flex

    Flex is known to have pimp drag and drop features. They are built into the SDK, and require a boolean and 2 event handlers to work. Mizz-nagic. However, there is another way to do drag and drop in Flex. It’s called the startDrag method, and it’s a party of Sprite. He has a stopDrag method as well. These methods are more efficient than doing your own emulation of drag and drop since they are built-in. The downside is they still have the same refresh problem, but you can fix that the same way you have in the past using a mouse move event handler, and calling updateAfterEvent on the event parameter.

    Using these 2 methods, you can build your own drag and drop interface that consists more of just using the Flex SDK list classes. They are, however, more low level so you have to do some more coding legwork.

    Introduction

    I built this Viewer Editor for a co-worker at work. The goals were thus:

    1. Needs to be done in 2 days.
    2. Worked on outside of work core hours.
    3. Implement important features to showcase ability to create interfaces vs. being feature complete.

    In short, a prototype for a demo. You know what that means kiddies: uber-hacks, kludgey code, and something you don’t bring to an interview (unless you are damn good at explaining context). The GUI you build can be saved as XML. This XML can be re-read in and the Viewer Editor will re-build the interface so you can edit it. This XML ultimately is read by a .NET web service that will build an HTML front-end based on the client’s settings and this layout XML. If a client wants something moved “20 pixels to the right”, you launch the interface, move the GUI element, and click save.

    So why show it knowing the code is bleh? A few reasons:

    • Shows how to do the ‘other’ drag and drop in Flex as well as the regular, built-in kind
    • Shows how to dynamically build forms through ActionScript using the Flex Form & FormItem classes
    • Shows how to use 50 billion bindings through ActionScript
    • Shows what you can build in 12 hours or less using Flex and Red Bull.

    Built JB Style; no Cairngorm overkill insanity here. Speed, people, speed! Code gen is for people who can’t type fast.

    You can view the Captivate screen cast, read the following, or both… or cross the border with a chicken and crowbar.

    Controls

    The Viewer Editor is made up of 3 panels to interact with laying out controls on the Canvas. The first is the Control Panel. This guy is configured via external XML. He dictates what you can drag and drop onto the Viewer Canvas.

    The Viewer Canvas itself is basically just a Canvas that draws draggable controls inside itself. You can select controls, drag them, as well as modify their properties in the Property Inspector.

    The Property Inspector shows the modifiable properties of a control when you select that control. You can also select the Viewer Canvas.

    Although there are 2 missing features such as deleting and changing z-order of elements, this could be easily done by having the Controller either remove an item from the currentViewer.children, or by changing the order of an item in the currentViewer.children.

    Conclusions

    Although Flex 2 is positioned as a way to build Enterprise applications, whilst Flash is for lightweight, speedy RIA development, clearly with the right attitude you can use Flex Builder as a prototyping tool. Drop the frameworks, ignore the code review, and down the caffeine.

    There is also a lot of potential for GUI WYSIWYG’s as front ends for CMS systems. From Scrapblog.com, gModeler, and many others. While it’s great to have a extremely configurable back-end, it’s also nice to have a quick, easy way to modify values in that back-end. It’s even more cool when users and clients can do this themselves in a controlled manner using a tool specifically built for allowing them to configure what they want changed most, without having to utilize a developer’s time.

    It’s fun to do prototypes and CMS’ in Flex.

    Viewer Editor – Screencast | App | Source | ZIP