Welcome to class! (A guide to writing classes for AS3 – Part I)

In this article we’re going to be taking your first tentative steps into the world of a developer (don’t worry, developing a chronic addiction to caffeine is optional). For the uninitiated it can be a scary place full of classes, objects and lots of other mind melting concepts. You wouldn’t be the first if you baulked at the thought and went back to the relative safety of the timeline. By the end of this series though, not only will you have written your first class, you’ll also have an insight into why developers like to play with them so much, and more importantly how classes allow you to make some kick ass programs! So prepare to get jiggy with terms like Objects, Classes, Inheritance and Object Orientated Programming

Take Note

If you are unfamiliar with the terminology, don’t worry if it’s all a bit overwhelming. Learning about programming is never something you do once! The important thing now is that you simply start building familiarity with the vocabulary, and the concepts behind them

Where not to begin…

Unfortunately, before we dive into writing code, to really get the most from classes it’s important to understand why we use them in the first place. If you’ve read any other tutorials on the subject, a term that comes up pretty quickly is Object Orientated Programming (or OOP for short). So other than the approximate sound an orang-utan would make, what the hell is OOP anyway? Well mostly it’s a big fancy word programmers like to drop every now and then to sound intelligent and convince management of our technical superiority (job security always is a worthy endeavour). Seriously though, it’s going to be very difficult to explain the ins and outs of OOP to someone who is still trying to wrap their head around the idea of writing just a single class. That’s why right now I think the important bit is simply that you’re aware of OOP.

In programming there is almost always more than one way to skin a cat, in fact there might be several! Unfortunately this range of possibilities gives you more than enough rope to hang yourself on a regular basis. You might think to yourself, well if it works well then hey – what’s the big deal? The answer is simple: CHANGE! Change comes in many different flavours from many different sources: Be it feature requests, bug fixes, or clients who asked for a calculator app and realised half way into the build that actually they want a social media widget. Point is change is an unfortunate reality that has to be (often grudgingly) dealt with. Now when you start poking about and changing things in your code, what you really don’t want is for the house of cards to start falling down, and to end fixing your own fixes and so descending into a never ending spiral of misery that’s sometimes affectionately referred to as “dependency hell”.

From a very high level point of view OOP is basically an antidote to this situation. The end goal is to write code that’s robust and easily maintainable so it can gracefully handle change without breaking. To this end OOP isn’t really a single specific method or technique per se, but rather a broad range of principles and ideas you should keep close to heart when writing code. Classes (and likewise many of their features) are essential building blocks in an OOP battle plan. The reason why I mention it here is that upon first contact writing classes may seem full of fluff and superfluous necessities, but have faith my young apprentice, everything has its place (which in due time will become clear as you begin building bigger and more ambitions projects).

Okay, well now that you have an idea of what OOP is all about, and excited about the thought of basking in its glory, chances are your first question is simply: “how?” Well like I said, it’s best not to worry about the specifics at this stage. Very often though, you’ll find that by the mere act of trying to write better code you’ll be employing OOP, and that’s exactly what we’re going to achieve here. Simply by using a couple of basic classes we’re not only going to save ourselves a great deal of time and effort, but we’ll also be implementing OOP goodness while we’re at it. But before we can really begin our journey into this brave new world, we first need to meet the humble Object.

In the beginning there was an object, and from this did everything come…

In Actionscript (as in most other programming languages) the object really is the mother of all things. The simplest example of an object is, somewhat unsurprisingly, an Object. It’s also quite easy to imagine all the things you see on stage as objects. So in fact a MovieClip is type of object, as is a Button, a TextField, a Sprite and so on. But it goes further than that. An Object isn’t only something that exists with physical dimensions, but it can be any kind of logical ‘entity’. It can be something very simple that contains only a few properties, such as your basic Object. A slightly more elaborate example is an Event. When you click on something with your mouse, Flash actually creates a MouseEvent Object that describes everything about the interaction, such the fact it was a click, the location of the click, what was clicked on and so forth. This object can then be used to provide all the relevant info that interested parties need to know about the actual click event.

Another example is an instance of URLLoader, again it doesn’t have any interface you can see, but it exists as a ‘something’ that allows your program to communicate to the great beyond of the interwebs. This was an important distinction I had to make in my mind: that an object can be virtually anything, so long as it can be described in some way. And cue Classes! (Finally!) Each different kind of Object obviously needs different properties, attributes and ways of performing tasks for them to be of any use us. And it’s Classes that allow us to define and describe these properties. So in reality when you call a stop() function on a MovieClip object, really you’re just executing the stop function as detailed in the MovieClip class. So in other words you’ve been using Classes all this time, even if you didn’t realise it!

In fact you can go have a look in the Actionscript Reference (also called the Actionscript API) and see that there are a multitude of classes already available to us! Many of them will be familiar objects such as the MovieClip, but a great many more will likely be unfamiliar. This by no means cause for alarm, because the truth is even seasoned programmers constantly lookup unfamiliar elements in the API. What might be alarming though is trying to make sense of the API (I can remember many expletives hurdled at the staff of adobe for trying to make their documentation as cryptic and obtuse as possible). The trick though is to realise that way things are described in the API is simply a reflection of the way they are described by their respective classes. So even if you’re not planning to write your own classes, you’ll still see a great benefit from understanding how they work. But of course if that was the case you wouldn’t be here, would you?

Of classes and men…

Usually the first analogy that’s reached for when explaining classes is that to imagine a piece of machinery such a car or aeroplane. If each part of the vehicle is an object then the blueprints are the classes. It’s a good analogy but instead I’m going to ask you to imagine a cake (because it’s easier to think of one object rather than several, or perhaps it’s just because I’m hungry.) So if we cast a Cake in the role of our object, then the recipe will take the lead as our Class. Really there’s only two fundamental components to a Class, which are properties (a list of ingredients) and methods (the preparation instructions). So all the properties would be variables (such as flour, eggs and so on) and the methods would be functions or actions to be performed (such as mixIngredients() and bakeInOven() ).

Okay great, so now we’ve got everything we need to make a cake, but I think we need to pimp out the whole idea of cake and make ourselves a ChocolateCake! While ChocolateCake might add a few extra things into the mix, such as chocolate to the list of ingredients, it’s going to be pretty obvious that ChocolateCake is going to have most of the same properties and methods as our regular Cake. Thankfully, using classes, it’s very easy for ChocolateCake to inherit all of Cake’s attributes, and use that as a starting point. The concept is called inheritance, and we refer to it by saying that a sub-class (ChocolateCake) extends the super-class (Cake). So with hardly any effort at all our ChocolateCake now has access to Cake’s features, but with the added benefit of more tastiness! And it’s in this manner (through inheritance) that we can say everything is an Object! By a chain (and sometimes a long one at that) of one Class inheriting from another, they all at some point inherited from the original Object class.

There’s one final topic we need to touch on before we actually create our first class. Let’s say we pass flash a Cake object, the Actionscript compiler has no way of knowing what kind of cake we’ve given it, in fact it probably doesn’t even know it’s a Cake in the first place (yes, it’s a pretty stupid beast sometimes). But if we tell it that Cake was made using the ChocolateCake recipe, then the flash compiler can make some pretty safe assumptions about it, such as the fact that chocolate is one of the ingredients. When you use a class in this sense it’s called a Data Type. A lot of errors arise in Flash because something was expecting a different data type from the one it actually received. Despite being a source of frustration this actually a good thing relating back to OOP, because it helps weed out potential errors before you even realise they’ve occurred.

Stay tuned for part deux where we’ll actually be getting our hands dirty with some code and finally attending to the business of writing our very own custom class.

  • http://www.masseffect.co.za Johnny

    Good cake analogy. Unfortunately, I want to byte a chocolate cake now (oh no he di’nt!)