Getting OOP to Speed with AS2

Getting OOP to Speed with AS2

“How to explain things to those new to Flash who are still putting code on buttons” is one of the framing statements in Ben Jackson’s article on Teaching OOP that really nails where new coders are coming from. Putting actions on buttons is kind of like learning how to draw a frog: a new ActionScripter learns how to make things happen right away, but creating a larger program requires the ability to compose and coordinate many things together, as allowed by the available programming tools

There are two main tools that Flash ActionScript 2 gives you as a programmer: the language, and the Flash environment itself.

  • The ActionScript 2.0 Language: ActionScript 2.0 without all the trimmings is pretty lean. If you know what the statements and operators do, that’s all I’m talking about. This is the bare, naked language that you’d learn in an introductory programming class. Do you know what all the statements and operators do? You really should. There’s not a lot to know, since the statements don’t do very much by themselves. That’s why intro programming courses can be so boring…they focus on the language itself, which is basically grammar. If you like grammar for its own sake, fantastic! If you’d rather see something move, you’re actually interested in the Script Environment.

  • The Flash Scripting Environment: This is what makes ActionScript 2.0 interesting…what you can do with Flash is all about what is provided to you already. With the language you issue commands, but without the Environment you have nothing to boss around. The Environment consists of all the special graphical objects like MovieClips and TextFields, built-in classes that provide useful functionality (like talking to a web server) or packages data (like Arrays and Strings). The environment also includes all the built-in functions that do Flash-specific things. The Script Environment is what “makes Flash Flash”. You could theoretically take the ActionScript Language and apply it to, say, a garage door opener, but the environment would be different because a garage door does different things: you’d have built-in objects like Motor and Sensor instead of MovieClip and Mouse.

You can think of the Environment as a bunch of pre-packaged objects that either do things on the screen, control the computer, or extend the language. The Language is what allows you to express yourself with those objects. Some objects are always around (System objects), some have to be created. Sometimes there’s just one of one kind (like the Stage), and at other times you’ll want to create multiple objects of the same type. That’s all we mean when we say AS2.0 is “object-oriented”. There is a lot of stuff in the Environment. Usually learning the language isn’t too bad, because programming languages tend to be largely the same in the set of features: they just are in different places. It’s sort of like when you climb into an unfamiliar car and are try to figure out how to turn on the headlights…the basic concepts are pretty much the same from car to car. Learning a new Environment, on the other hand, is like starting a new job at a new workplace. Eventually, you learn what does what in the company, learn the new jargon, and adapt to the way things are done. The best reference books I’m aware of are the ones from Colin Moock; however, I’m not sure how accessible they are to the beginning Actionscript Programmer who just wants to know what’s what.

Objects versus Object Oriented Programming

Because of the amount of literature written on Object Oriented Programming, it sounds like a really complex subject. From the language and environment perspective, though, it’s not complex. All it means is that you can group functions and data into one lump, almost like a little mini-program, and we’re going to call this lump an object. That’s it. Many of the really cool features of the Flash Script Environment are packaged in these object thingies, so to use them we need to use the other bits of AS2.0 that allow us to access the data and functions inside them. Hey…that’s being object-oriented! Don’t get me wrong…there is a lot to Object-Oriented Programming (OOP), but even that is something of an overblown concept. OOP is a set of best ideas regarding the use of objects to make life better for the programmer. In software engineering, we generally want features like scalability (“what if I wanted to make this really big?”), maintainability (“can my coworker work with my code if I’m on vacation?”), robustness (“does it always work?”), expandability (“I want to add a couple new things and not do a whole lot of extra work”), and so on. These features are not specific to OOP, but OOP was designed to help implement them in an easier way. An OOP-capable language just provides the special statements to make it easier to express those ideas in an object-oriented fashion; in other words, you can’t easily create an object if there is no command to do it. There is nothing stopping you from using Objects independent of OOP practice. And you shouldn’t feel ashamed of that, if it gets the job done. If you’re just getting used to the idea of using Classes, think of them as just a group of related functions that have their own shared data, and try to structure your code that way. The “mini program” analogy isn’t a bad one. I think you’ll find, as you play around with the idea of grouping related functions together, that object-oriented questions start to come up naturally. Then, all that fancy OOP reading on inheritance, subclassing, composition, and polymorphism may start to make sense. In the meantime, just screw it…they are just labels for simple concepts that we’ll talk about later. ##But Wait, OOP isn’t the Problem I feel bad for saying this just as you were starting to feel better about OOP, but this is not the real challenge in learning ActionScript 2.0 in Flash. If you’ve had more than one button on the screen, you’ve experience the chore of keeping track of what code fragment is doing what when something gets clicked. This is event driven programming, and OOP doesn’t make these challenges don’t go away. You need to have a grasp of how events drive the flow of control before you can really do anything cool in Flash. Challenge: Adapting Old Techniques from the Internet Compounding the problem is that the majority of code fragments on the Internet use event methods that date back to Flash 4 or 5. As soon as you try to use them in an OOP-y way, everything breaks. That’s because the event handlers you are used to writing look like this:
    // mc is a movieclip instance on the Stage
    mc.onPress= function () {
        trace("boo! we are pressed!");
    }
You might be tempted to try something like this with objects:
    // DoSomething is a class we make with a function called pressed() in it
    var pressHandler = new DoSomething();

    // mc is a movieclip instance on the Stage
    mc.onPress = pressHandler.pressed;
That won’t entirely work, because the onX handlers for MovieClips are implemented as a function callback, which doesn’t entirely work with functions inside an object. BTW, “functions inside an object” are called methods. The loaded() function will get called, sure, but none of the other variables (called properties) in your objects will be accessible! There’s a technical reason for that, but I won’t go into it now. The takeaway is this: movieclip callbacks do not work with objects. You need to find another way of detecting events; in Flash MX 2004, that’s by using listeners instead of callbacks; for MovieClips, you’ll want to look at the Mouse and Keyboard objects to achieve the same functionality with “Listeners”. Yet another way is to manually reconnect the object context. Challenge: The Compiler Doesn’t Help You Unless You Help It How many times have you discovered your code isn’t working because you had the wrong NAME of an object or property, and Flash didn’t tell you? That’s what I’m talking about…this reminds me of the head-in-the-sand mentality of not telling someone that the house is burning down because it might be “upsetting”. Fortunately, in AS2 starting with Flash MX 2004 we could add type-checking, which allowed the compiler to catch such problems. The good news is that it works really well. The bad news is if you’re too lazy to add datatypes to your variable declarations (and objects are a kind of variable), it doesn’t work. The properly typed example would have been like this:
    // LoadDisplay is a class we make with a function called loaded() in it
    var pressHandler :DoSomething = new DoSomething();
The example still won’t work, but if I had done this by accident:
    // pressMe() doesn't exist in the DoSomething class
    mc.onPress = pressHandler.pressMe;
…the compiler would have caught that loadedMovie wasn’t actually a method defined in the LoadDisplay class. And I would have one less problem to debug. ##That’s All For Now So that’s on my mind right now. What I’m trying to say overall is this:
  • Conceptually, objects are just a way of packaging functions and data together.

  • Object-Oriented Programming (OOP) is a methodology for creating programs with desirable qualities like maintainability, robustness, and so forth. AS2.0 has new statements in it—most notably, class and new— that allow the programmer to create objects.

  • There’s a lot to OOP, but it’s actually pretty common sense stuff. All those mysterious keywords associated with the class statement—private, static, implements, and so on—are directly related to creating objects that support the best practices in OOPing. But you really don’t need to use them until you’re ready.

  • The other main challenge in using AS2 in Flash is event-driven programming, because the tried-and-true methods you’ve used in the past don’t quite work with Objects. The reasons are a bit esoteric, and are related to Flash’s sordid past. However, there are ways of working around it.

<

p>I haven’t yet touched on how to make the connection between the big ideas in your head and these topics. For that, you need to have a different methodology: Learning how to structure your ideas into shapes that can be expressed through the script language and script environment. That’s when things really start to get interesting…

8 Comments

  1. Dave 14 years ago

    Some notes to myself: It was interesting to write this, though I’m not sure really how useful it is to a general beginning programming audience.

    The main point, I think, is that “If that code fragment from the Internet doesn’t work, it’s not you. It’s Flash’s long and ancient history creating something of a jumble. There are new ways of doing things, and old ways that should be forgotten. Figuring out which is which is the challenge.”

    Then, just launch into a “here’s something that works” article, with downloadable examples.

    ——-

  2. Dave 14 years ago

    Another topic I’m dancing around is how to learn the stuff. For me, there are a few basic steps:

    <ol>
    <li>Learn the Syntax and the Concepts behind the base language. Most mainstream languages are pretty much the same: it’s either C++ or some form of (ugh) BASIC.</li>
    <li>Get a Map of the Environment. There’s a few steps to this too…knowing what you can DO, knowing what piece of code DOES it, and then figuring out how to make the language actually do it.</li>
    <li>Assemble the best possible reference documentation, even if I have to piece it together from photocopied scraps. Usually the environment is very large (Flash’s map is maybe medium-sized), but you can start to identify areas where commonality occurs like when you live in a big city. Using Boston as an example, you know there’s “Chinatown”, “The Leather District”, “The South End”, and you know what to expect out of each neighborhood.</li>
    <li>Assemble a high-level overview of what each major code library or special function does, conceptually. This usually means you have to “get inside the head” of the person who made up the language or code library. They will use different terminology, have different ways of approaching things, and so on. You know how some kids are finicky about the way their sandwiches are cut, and it makes no sense until you really get into the psychology of it? SAME THING. Some things will make sense, some you will just have to accept as the way they are. Or, you just say NO and learn another language (Perl falls into this category for me…I can’t stand it).</li>
    </ol>

  3. Ben Jackson 14 years ago

    Great article Dave, and thanks for the props.

    Just put up a sequel that goes into a bit more detail about the concepts and the language of OOP.

    One thing I think you neglected to mention is the now very widespread use of open-source tools, in particular MTASC, swfmill, and Eclipse, to create swf content. OSFlash has a pretty comprehensive directory. The focus is increasingly shifting away from “What can we create in Flash?” and more towards “what can we do with the (now open) swf format?”

  4. Dave 14 years ago

    Hey Ben!

    That’s a good point. In my head, I see those as tools outside of the “environment” I’m talking about (software code modules). Everything else I talk about I think still applies.

    I also haven’t looked too closely at MTASC etc, since I have a perfectly fine Macromedia-based workflow here. A number of years ago I looked briefly at Laszlo well before MTASC was out—-they were one of the first, I believe, to recognize the ubiquity of the SWF player—-but I still had a decent workflow then and didn’t worry about it.

    One thing I’m thinking also is that there’s a way to bridge the gap between “attaching AS to buttons” and “oop event driven code” with a hybrid timeline-based approach. I used something like this on a recent project, because it was fast to prototype. With a little formulization and creation of some safety type-checking classes, it might be a nice approach to take. I need to verify that some things work the way I think they will first, though.

  5. Ben Jackson 14 years ago

    The difference between Laszlo and MTASC (besides the fact that the latter is much easier to spell) is that Laszlo, from what I understand, is an open-source framework for developing Rich Internet Applications. MTASC is actually a compiler, which produces swfs by “injecting” (I hate that term) classes into an existing swf (it can also create them from scratch if you have no library assets to worry about).

    Just to play devil’s advocate, I also thought I had a decent workflow before I tried using MTASC ;)

    For me, the advantage to OSFlash is that my tools are modular instead of wrapped into an all-in-one solution. I don’t use 10% of the features in Flash MX 2004, and the other 90% just add bloat.

    I don’t know how good Flash’s project management is because I haven’t tried it, but at least Grant Skinner has found it lacking enough to [write his own]. I just use subversion, and like the fact that I can control it from my text editor (where I spend 95% of my development time).

    I try to keep as much of my code as possible in one frame. Where I use the timeline, it’s only for short animations that are then controlled by my classes. What kind of approach are you thinking of?

  6. Dave 14 years ago

    Laszlo is essentially another OSFlash, organized around different principles. At the time I was looking at it, I found it a little too different for my tastes… the core was an XML document that you lay out the application, and then you could insert scripts as attributes (or somehow bind them to functions defined elsewhere). It was almost like using a visual form-based dev environment, except your dev environment ended up being Emacs :-) MTASC is a lot more like a traditional workflow using an IDE wrapping a MAKE process (which is what Flash MX 2004 sort of does too).

    Flash’s project management was not impressive when it came out, but it worked (eventually after being patched…the Mac side didn’t work at all on release). It was good enough though when I started Showing Evidence in Nov 2004, so we stuck with it until we wrapped this year. We did actually look briefly into compiling with MTASC on the Mac because the MX2004 compiler was incredibly chuggy, but MTASC choked on some of our source and we deemed it not worth rewriting at the time. The App would have been a good one to test with though…I may do that this week. The flash movie is just a stub, that has one #include in it. It also serves to hold graphics resources. Then, I used the Flash IDE as a big text editor, which may seem wasteful, but it does a good job enough job. Incidentally, subversion works just fine with the Flash IDE for source control. It actually helps get around the old compiler bug where if your file timestamps get out of sync with the pre-compiled modules (which any real IDE would have fixed by including a MAKE CLEAN type of option, bah).

    The kind of stuff I’ve been doing lately has been more long-form animation with bits of interactivity, so working within the Flash environment actually makes a lot more sense. I tend to pile on the code in just the first frame, and then I quickly-prototype look and feel with regular Flash timeline and movieclip actions. If I need a spot of interactivity, I use functions defined in the main file. It’s good for when I’m doing run-and-gun one-of-a-kind interactives that need visual approval before implementation, but it’s not quite ideal.

    That said, I should look at MTASC-based workflow…I’ve been intending to for quite some time. I did occassionally look at the alternate editors for features like text folding and class browsing, but a year ago they didn’t seem quite solid enough to convince me to switch.

  7. carl 12 years ago

    Dave,

    Excellent article. There are legions of as1-as2 people making the as3 jump. I’ve been eating up anything i can on oop concepts. Been doing a lot of reading… and not so much understanding. the more i read… the more it sets in. This article / series is extremely well written. I believe you will get through to your target audience. Your efforts are greatly appreciated. I especially enjoyed

    “just screw it…they are just labels for simple concepts that we’ll talk about later”

    i find myself too often getting in over my head to quickly and getting overwhelmed. Nice to here someone emphasizing a “stick to the basics” approach for beginners.

    best,
    carl

  8. stani 12 years ago

    hai DEV,
    It is really a great writing about AS i’ve ever read before. I hope u’ll write more. I like your way of approach about OOP/Script. You can write a book about it in your “style” of approaching Programming Languages (particularly i need OOP and AS 2.0).. i’ll buy it.