Posts Tagged ‘OOP’

Huge list of external libraries


Monday, November 9th, 2009

LibrariesI was in the process of collecting all of my favorite Actionscript 3 class libraries, when I came across this giant list of them. Rather than double up the work, I wanted to share it with everyone! This guy put a lot of time into organizing it, and its a very useful list. If you don’t know how to use external libraries, check out my article on them.

(more…)

Adobe Blogs: Presentation Patterns in Flex


Wednesday, October 21st, 2009

FlashI came across this great article by Paul Williams on the Adobe Blogs. It goes into detail describing quite a few different Presentation Design Patterns for use in Flex (could be used in Flash as well).

Design Patterns, for those who don’t know, are general reusable solutions to commonly occurring problems(Wikipedia). They are a key component of Object Oriented Programming, and is not Actionscript-specific.

The patterns explained (with nice examples and source files) in the article are:

  • Autonomous View
  • Supervising Presenter
  • Presentation Model
  • View Helper
  • Code Behind
  • Passive View

Read through the article, and if you get stuck, drop a comment here and I will try to help out. You will not be disappointed, design patterns are probably your most precious ally when it comes to development.

Using external classes in Actionscript 3


Wednesday, October 21st, 2009

FlashExternal classes are a great way to get lots of advanced functionality in your applications, without having to write custom code. This may seem simple to most of you, but I remember when I was just starting out in Actionscript 3, and I could’ve used an article on this.

There is a huge collection of classes available online for free, a few of which live here on my site! You can probably find a class to do nearly anything pretty easily. There are classes that tween properties, play videos, mp3’s and all kinds of other stuff.

One of my favorite classes is TweenLite, which is a very tiny tweening class. Some other good ones include Papervision3D, Adobe’s Libraries, the Google API’s and as3DMod.

Using your first class

If you’ve never used an external class before, it can seem a bit confusing. Don’t worry, its so simple, and extremely useful! Let’s go through an example, using my com.dyc.video.VideoPlayer class. All of that com.dyc stuff is nothing to be confused about. It is merely the folder structure that organizes the classes. When you download my VideoPlayer class, it will unzip to a folder called com, which has a folder inside of it called dyc, and so on, until you hit a file called VideoPlayer.as, which is the actual class file.

Drop the com folder in the same folder as the FLA (or flex source) you want to use the VideoPlayer on. First thing you need to do is import the class. At the very top of your DocumentClass (or other class file where you’ll be using the imported class), you start with the import statement:

import com.dyc.video.VideoPlayer;

This loads the Actionscript class into memory. To use a class, you normally have to create an instance of it. You can do this by declaring a variable, and giving it a type of VideoPlayer(or whatever class you are importing).

var videoPlayer:VideoPlayer;

Now you have somewhere to access the class from. If the class contains a display item, something that will be shown in flash, you will probably want to set the x and y coordinates of the class, then addChild() to put it on the stage. You will also have to instantiate the class(unless its a Singleton class, but more on that in a later post). To instanciate, you merely create a new instance of the class, through the variable you just created.

videoPlayer = new VideoPlayer(320, 240, videoURL);

Sometimes a class has the ability to pass variables to the constructor. This sets up the class with your specific data. In the previous snip of code, we passed 3 variables to the new VideoPlayer() instnace. The first two are the width and height of the video player and the third is a variable that points to a URL of an FLV.

If you wanted to run a function called togglePause() on the VideoPlayer, you would access it through the instance you made.

videoPlayer.togglePause();

That is basically it. You can read through the documents of any classes you download, or read through the class itself to find out how to use it. Most classes have very good documentation, so they’re very easy to figure out.

Clean Coding Makes You Worth More Money


Wednesday, October 14th, 2009

Clean Code!If you’ve just started writing Actionscript 3 applications, you are probably not too familiar with most of the “best practices” for coding. Even if you’re like me, and have been developing for half your life, chances are you don’t always follow the rules. Some of us didn’t even know there were rules. Let me take that back, rules sound so constraining. Chances are, you don’t follow all of the known best practices for efficient, easy-to-digest code.

Some would argue that clean coding, and best practices won’t directly result in more money coming in for your projects. I disagree. While you can’t exactly charge a client an extra $10 an hour and say it’s because you use “best practices” and “clean code”, you can make yourself easier to work with, more efficient, and more likely to get return clients.

Let me break that last bit down for you, clean coding makes you:

  • Easier to work with
    Following common best practices will enable other developers to quickly figure out, debug, and augment your code. Even if you are not working in a team environment, you can quickly earn the reputation of a spaghetti programmer (sloppy, hard to follow code). This is not something you want to happen, it can affect your chances of getting that great job or project you need.
  • More efficient
    If you are spending less time trying to figure out how all that sloppy code works that you wrote weeks or even months ago, you are getting more done, in less time. This means you are being more efficient. Less time + more tasks = more money per hour!
  • More likely to get clients to come back
    This is especially true if your clients ever see your code. I know a few years ago, before I started paying close attention to how well I wrote my code, clients with even minimal Actionscript experience would mention that my code seemed sporadic!

Big picture, better coding techniques = more personal worth. Now let me go over some poor coding techniques , most of which I used to practice without knowing there was a better way.

1.) Variable declarations spread throughout the program

We’ve all seen this, variables declared randomly all over the code. Every time some new variable is needed, you just create it right then, and leave the declaration were it was written. You end up with rouge variables being created all over the place.

The proper way to do this, is to keep ALL of your variables declared up at the top of your actionscript file. I also suggest ordering your variables in some sort of organized fashion.  For example, some times I will sort my variables by type:

// Array's
private var myArray1:Array;
private var myArray2:Array;

// Sprite's
private var mySprite1:Sprite;
private var mySprite2:Sprite;

// Boolean's
private var myBoolean:Boolean;
public var myBoolean:Boolean;

2.) Poor Event management

Every time you make an even listener, don’t forget you created it! As soon as the event has triggered, remove it (unless you need to keep listening for it). For example, if you have a listener on a button that goes to a new section and removes the button, remove the listener as well!

myButton.addEventListener(MouseEvent.CLICK, buttonHandler);

private function buttonHandler(e:MouseEvent):void {
    myButton.removeEventListener(MouseEvent.CLICK, buttonHandler);
    launchSection(newSection);
}

If you don’t pay attention to your event listeners, they can easily get out of hand. It’s much better to think out each event listener as you create it, and remove it when you can.

Another sorta hack you can use is weak references in your event listeners. The 5th argument in addEventListener is useWeakReference, and if you pass true, it will allow the actionscript garbage collector to grab Objects you’ve removed form the display, even if you have an event listener still on it. Without weak references & removing all of your event listeners, you could end up with a memory leak.

3.) Not removing Objects from memory

Every time you create a reference to an Object, you are taking that much memory from the computer. If you don’t remove each of the Objects you create, you can end up with another memory leak, especially if you are dynamically creating Objects.

It’s easy to think that removing an Object from the display removes it from the memory. This is far from the truth. You have to remove the Object from the display, remove all references to the Object, including event listeners, AND null out the Object.

// Create your Object
var myObject:Object = new Object();
myObject.addEventListener(CustomEvent.Event, eventHandler);
addChild(myObject);

// Later
myObject.removeEventListener(CustomEvent.Event, eventHandler);
removeChild(myObject);
myObject = null;

4.) Not Using Object Oriented Programming

The perfect way to organize your code is by using OOP. I have written an introduction to Object Oriented Programming that should get you started writing OOP.

4.) Not Keeping Your Code Clean

What is clean code? I would say its when you can read the code like a book, without the need for comments. The methods are all laid out in a somewhat linear fashion. They lead into one another, and are grouped together based on their relationships to each other.

This brings me to the next one:

4.) Using Bad Naming Conventions

Always name your variables & methods with clear intentions. Anyone should be able to understand what something does just by reading its name.  Don’t use funny names, try to make the names as informative as possible.

If your function hides all of your nav items, you could call it hideNavItems(). If your Array holds a reference to a collection of Sprites, you can name it spriteHolder.

More Resources

As you can see, there are plenty of ways you can make your code easier to understand & update. This will be beneficial not only to you, but to anyone who ever has to update or adjust your code in the future.

The biggest thing to take from this, is that by witting clean code, you increase your worth as a developer. Don’t take my word from it, give it a shot. Spend some time learning ways you can write cleaner code…

For now, you can start with some links to books & articles on the subject:

If you have any clean coding techniques, share them with us in the comments!

http://www.amazon.com/ActionScript-3-0-Design-Patterns-Programming/dp/0596528469/ref=sr_1_1?ie=UTF8&s=books&qid=1255579216&sr=1-1

Introduction To Object Oriented Programming


Sunday, October 4th, 2009

FlashOne of the most important things to understand when building large-scale, expandable Flash projects is Object Oriented Programming, or OOP for short. According to Wikipedia:

Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” – data structures consisting of datafields and methods together with their interactions – to design applications and computer programs.

Basically, its a style of programming, that makes things much easier! I’m sure you’ve seen projects that had hundreds, if not thousands of lines of actionscript written to make all the magic happen. If the original programmer didn’t use an “OOP style” of programming, you would probably have to spend a good few hours just trying to figure out what the program does, let alone change anything and not cause more bugs in the process! This type of programming is sometimes refereed to as “Spaghetti Code” because you have to follow long twisty noodle-like paths to get around.

A more effective way to program is to take the Object Oriented approach. You organize every different piece of the program into different Classes.

An Object is a collection of attributes & behaviors encapsulated into a one small entity. The attributes are all of the variables. For example, if we were creating a BabyBoy() Object, some attributes we may have are eyeColor, height, weight, age, etc. These variables hold all of the data that is contained within the BabyBoy() Object. Some behaviors we might find are eat(food:FoodObject), sleep(duration:Number), dance(bpm:Number).

If the behaviors (methods) I just showed you don’t make any sense, you should read up on Actionscript Functions.

So now that you know what an Object is, you need to understand how Instances work. When you have an object class, you don’t actually reference the class, you create an instance of it. For example:


var myObjectInstance:Object = new Object();
// Then we adjust the attributes (variables) & run
// the behaviors (methods) on that instance.

myObjectInstance.myVariable = "New Variable Value";
myObjectInstance.myMethod();

Classes are blueprints of an Object. They organize all of the variables & methods that each Object can use. A basic BabyBoy() Class would look like this:


package com {
 // import the class we are going to extend
 // (More on this soon)
 import flash.display.Sprite;

 // import the custom classes we use
 import com.food.FoodObject;

 public class BabyBoy extends Sprite {

 private var eyeColor:uint = 0xFF0000;
 private var heightInInches:Number = 13;
 private var weightInPounds:Number = 12;
 private var ageInDays:Number = 4;

 public function BabyBoy() {
 // Constructor functionality
 }

 public function eat(_food:FoodObject):void {
 // Eat functionality
 }

 public function sleep(_duration:Number):void {
 // Sleep functionality
 }

 public function dance(_bpm:Number):void {
 // Dance functionality
 }

 }

}

As you can see, everything that you want an instance of the BabyBoy class to be able to do, has to be built into the Class. Let’s go through the class one section at a time.

First off, at the top, we declare where the actual class is located: package com { is actually saying “this package lives inside of a folder called com”. So next to your FLA & Actionscript file, there would be a folder named com. This is where you organize and hold all of your Class files. You want to keep it as organized as possible.

Next we import all of the Classes we are going to use in this particular Class. We then declare the Class, extending the Sprite Object:

public class BabyBoy extends Sprite {

The name BabyBoy must match exactly the file name (minus the .as) and the first function (constructor) name.

After the class name, you declare the variables you are going to be using. If you use private before the var, the variable is only accessible from within this class. You will not be able to access it from another place. However, if you needed to access it from outside of this Object, you could change the private to be public. Now you can access the variable from anywhere, just target the class instance then the variable:

myClassInstance.myVariable = "new variable value";

trace(myClassInstance.myVariable);
// displays "new variable value"

Next up is the constructor function. The name of the constructor must match the file name (minus the .as) and the Class name. This method executes when an instance of the class is created. You want to use this function to call other functions that set up the object, or do any procedures you need to make the Objects functionality work.

Finally we have the rest of the public & private methods/functions. These are the brains of the Object. You call on these to make the Object work.

Let’s take a sec and do a visual re-cap:

Object Oriented Programming

Let’s say for a particular project, you would be needing classes for BabyBoy, BabyGirl, YoungBoy, YoungGirl, OldMan and OldWoman. You would probably want to have a folder (package) inside of the com folder called “people”. Inside of people, you would put all of your classes.

If you needed to add another class or two for Dog() & Cat() Objects, you would create another folder inside of com called “animals”. This keeps all of your classes organized into thought-out structures. It’s easier to locate the class you need when your package structure is well designed.

In the BabyBoy() Class example, we are extending the Sprite() Object. This is called Inheritance. Just as when you inherit money from a rich relative, when you extend an Object, you inherit all of its variables & methods. Sometimes you can start out with a fresh class, and have no need to inherit the characteristics of another Object. However, sometimes it would save you tons of time to extend a Sprite() Object instead of going from scratch. You get dispatchEvent() for sending out Events, addChild() for placing DisplayObject’s into the Object, and so forth.

When starting to write a new class, you should think about what your class is going to need to do, and see if there is already a class written that has some or all of that functionality built in. If you find one, go ahead and extend it for your new creation, and add the custom parts that were not inherited.

Encapsulation is an important part of OOP, which pretty much means hiding the details of how an Object does what it does. You expose an Interface to use the Object, which is made up of the public methods in the Class.

A good way to imagine Encapsulation is to think of a computer. You don’t need to know exactly what is going on after you hit the power button, you just need to know that pushing that button turns the computer on. You also don’t need to know how the keyboard sends the letters to your screen, you just need to know it does.

So you build a good collection of public methods that cover all of the stuff you’re going to have to use to actually use the Object, and the rest of the functionality is broken up into small private methods that do individual tasks.

That covers the basics of Object Oriented Programming. If you still can’t wrap your head around the ideas, don’t worry, sometimes it takes a few times to sink all in. If you have a specific question, just leave a comment, and I will try to answer everything & revise the article to explain it a bit more clearly.

I would also suggest taking a look at some of these resources: