Category Archives: OOP

AS3 Primitives

*Edit: I have found that I am wrong about the following (as shown from the comments). In AS3, numbers are in fact placed in their wrapper classes. My interpretation are wrong. You can keep read the following if you want to know how it DOESN’T work. Basically what I describe is how Java works. AVM2 doesn’t do this, it wraps everything as an object… Sort of strange as there are performence gains using primitives.

I read a post recently that asked whether AS3 Number objects are actually treated as objects in AS3.

Number, int, etc are primitives. Just like in Java, these types have their Object class associations in case you want to create instances and call various methods that come with the Number class. For example, the Number class has functions like toFixed for number precison and accuracy.

The concept of primitives are sort of confusing to newer programming as they go against object oriented programming. In fact, in Smalltalk, one of the first OOP languages, EVERYTHING is an object. The +, -, *, etc are treated as “messages”.

In Smalltalk, since everything is an object and has messages passed, you have to specify the function for “+” and “-“. Primitives in higher level languages don’t have that just for this reason. You don’t want to have to write the code to add two numbers together do you? The concatanation syntax for Strings is also “+”. Notice how “-” is not properly handled with Strings while it is with Numbers… 

Also, in terms of an ideological argument, Number can be said to be the lowest form to describe an object. Think of the composition property of object oriented design. Everything is made of objects that are made of objects that are made of objects… There are theoretically an infinite amount of layers in-between.  Object oriented design is the practice of selecting certain layers and abstracting the rest. But at the very core, every object has to be made up of primatives (more specifically, since Strings can be represented as numbers). Think of any class you’ve ever programmed. The properties will always have either primatives or other objects. If you recurisvely loop through other objects they will all also be made up of primatives (unless they have no properties at all… that’s sort of an anomoly and bad programming design dependant on “isA” relationships… so I’m going to avoid that tangent).

Primitive types are the building blocks. Just like materials are made from atoms… you can’t really go lower than Numbers in describing an object. Additionally, primitives are passed by VALUE rather by reference.

Here’s another post I wrote a while back that went a little deeper into this concept.

AS3 EventManager Class: removeAllListeners

I heard about a class that Grant Skinner wrote called Janitor that was supposed to help keep track of listeners, but I couldn’t find it. Consequently, I wrote my own “EventManager” class for a gaming project I’m working on which keeps track of Event listeners in a project.

As all Actionscript 3 developers know, one of the biggest annoyances is keeping track of listeners and ensuring objects are collected in memory. This class does a lot of that for you, and even has a method removeAllListeners which has different filters. So let’s say some listener keeps calling a function, you can remove all listeners that point to that function. Or let’s say you want to remove ALL key listeners.

Here it is:

*EDIT 9/30/08: EventManager Updated. Click here to get it.

For example, let’s say you have something like so:

var obj:MovieClip = new MovieClip();
var obj2:MovieClip = new MovieClip();
obj.addEventListener(Event.ENTER_FRAME,Test,false,0,true);
obj = obj2; obj.removeEventListener(Event.ENTER_FRAME,Test); // Does NOTHING!

Test will still be called every frame! Even though weak reference is set to true and there are no more references to obj! This is not good! But with EventManager…

var obj:MovieClip = new MovieClip();
var obj2:MovieClip = new MovieClip();
EventManager.addEventListener(obj,Event.ENTER_FRAME,Test,false,0,true,true); // last parameter actually adds the listener, see documentation in class of why this last parameter exists.
obj = obj2; // Now we have a bunch of options, any of the bottom lines would work EventManager.removeAllListeners(null,Event.ENTER_FRAME); // will remove all Event.ENTER_FRAME listeners
EventManager.removeAllListeners(null,Event.ENTER_FRAME, Test); // will remove all Event.ENTER_FRAME listeners that call Test
EventManager.removeAllListeners(null,null, Test); // will remove all listeners that call Test EventManager.removeAllListeners(); // will remove all listeners

The only problem with the class is that this version does not distinguish useCapture events… But big deal. Maybe I’m naive, but how often does anyone actually set useCapture to true?

Anyway, if this class gets a lot of attention I’ll put it as open source on Google Code. Then someone else can add in functionality for useCapture.

This class was such a pain to code. AS3’s Dictionary is the only sure fire way to index objects as objects (as Array uses the result of toString() for indexes), but because (for some reason that’s beyond me), Adobe decided not to have a length property in Dictionary, my life was made very difficult. There might be some bugs, but based on my initial tests everything seems to be working fine. I wonder how Grant’s Janitor class is compared to mine. I really couldn’t figure out any other way to write the function definitions for EventManager.addEventListener and EventManager.removeEventListener (having actuallyAddListener and actuallyRemoveListener as the last parameter). I wish AS3 had a way to get the memory location value of an object. Something like Object.toMemoryString or something. That way Arrays could be used and the Object.toMemoryString value (which would be unique for every single object) could be used as keys.

If you decide to use this class, please let me know so I know my work hasn’t been in vain!

Object Oriented Programming without a Computer

Artists see the world as a canvas. They represent environments, objects, and abstractions with shapes, shades, and colors. Pride and honor can be shown in a sculpture, or love may be represented with red colors and heart shapes. Architects envision the world as a blueprint; objects have structure and forces acting upon them from other objects. Just as a bridge is supported with suspension chords and metal, a family is strengthened with care and unity. Profession influences perception, and while outlooks on space and matter may differ, none are right or wrong – only different. But these professions and perspectives are kept in mind when programming languages are developed. Today, one of the most common programming ideologies is object oriented programming (OO). Object oriented programmers don’t picture the world as a canvas or blueprint; alternatively, OO programmers envision a hierarchical world composed of hierarchical objects with polymorphic, encapsulated actions and properties. There are four fundamental principles of object oriented programming: composition, inheritance, polymorphism, and encapsulation. Each attribute can be explained without a computer in a non technical (Java based) perspective, and some visibility represented in an Adobe Flash environment.

Scooby Doo is a famous detective dog from children TV and books. The charismatic, friendly, cute dog detective helps his friends solve mysterious.

In Java (and other OO programming languages), Scooby could be represented as a class.


public class Scooby
{
}

In Flash, Scooby can be represented as a Movie Clip with a picture of Scooby inside of it.

In this picture, Scooby has a bright, blue collar around his neck. He also has a long tail and a big nose. The idea that Scooby has these three objects and more is the composition concept of object oriented programming. Modifying the class to fulfill this design ideology is very easy in Java.


public class Scooby  

{  

    public Collar myCollar;  

    public Tail myTail;  

    public Nose myNose;  

}  

ScoobyCollar, ScoobyTail, and ScoobyNose are all objects that belong to Scooby; therefore, they are stated inside the Scooby object. In Flash, a Movie Clip that is placed on the stage can have multiple Movie Clips inside of it. Consequently, a representation of Scooby in Flash could be a movie clip called Scooby with three movie clips called myCollar, myTail, myNose. Every object has its own properties and actions, and consequently Flash allows code and properties to be added to actual objects. Flash and Java are two environments that use the same idea of building blocks. The building blocks of Java are floating point numbers while the building blocks of the visual Flash environment (excluding Actionscript) are vectors, bitmaps, and video. This means that objects can be broken down to their compositions, and their compositions can likewise be broken down and eventually they will all break down into the building blocks of the language. For instance, a soccer ball has color (a hexadecimal number) with bounciness (a number), weight (number), or a logo which can be itself broken down to objects that have numerical representations. In Flash, a movie clip is composed of vectors, videos, bitmaps, or other movie clips.

Inheritance, another fundamental aspect of OO design, is the concept that every object inherits identity from another object. For example, Scooby is a dog, a dog is an animal, an animal is a living being, and a living being is… an object. Scooby is a dog because Scooby has all the properties and actions that every dog possesses. One could claim every dog barks, has four legs, and has a tail. One could also say that not all dogs have a collar, have a big nose, or a long tail like Scooby’s. Clearly, there can be an infinite amount of classes between animal and living being, but the idea is that everything (eventually) is a subset of an object. Objects have attributes from more general objects, but have specific attributes that only it and its children objects keep. In Java, this concept is represented with the extend keyword. “Scooby extends Dog” means that Scooby is a dog and inherits the methods and properties from Dog.


public class Scooby extends Dog  

{  

    public Collar myCollar;  

    // Notice how tail and nose was removed from here and added to Dog  

    public Scooby()  

    {  

        super();  

        super.myNose = new ScoobyNose(); // ScoobyNose extends Nose  

        super.myTail = new ScoobyTail(); // ScoobyTail extends Tail  

    }  

}  

  

public class Dog  

{  

    public Legs myLegs; // These properties are accessible in Scooby  

    public Tail myTail;  

    public Nose myNose;  

    public void Speak()  

    {  

        System.out.println(“Ruff!”);  

    }  

}  

Unfortunately, the concept of inheritance does not apply as easily with Movie Clips. Flash takes the approach that a Movie Clip is an object, and subclasses of Object are created as new movie clips and shapes are added to the original movie clip. For example, a vector drawing of a basic car is in a movie clip called Car. The developer in Flash can rename Car to BMW. According to the idea of inheritance, the car should be easily modified to create a BMW since a BMW inherits all the elements of a car (four tires, has an engine, etc..).

Polymorphism is the idea that two objects can have the same input but have a different output. A dog and a cat can both speak (which can be said to be an action of SpeakableAnimal which both a dog and a cat extend), but one says “Meow” while another says “Ruff”. In fact, Scooby says neither, he says “Scooby Dooby Doo!”

Therefore, the design needs to change in Java. The method Speak needs to be “overloaded”, which means the name of the action is duplicated but the implementation changes.


public class Scooby extends Dog  

{  

    public Collar myCollar;  

  

    // Notice how tail and nose was removed from here and added to Dog  

    public Scooby()  

    {  

        super();  

        myNose = new ScoobyNose(); // ScoobyNose extends Nose  

        myTail = new ScoobyTail(); // ScoobyTail extends Tail, therefore a ScoobyTail can be constructed even though myTail is of a Tail Type  

    }  

    // Overloaded action  

    public void Speak()  

    {  

        System.out.println(“Scooby Dooby Doo!”);  

    }  

}  

  

public class Dog extends SpeakableAnimal  

{  

    public Legs myLegs;  

    public Tail myTail;  

    public Nose myNose;  

    // Overloaded action  

    public void Speak()  

    {  

        System.out.println(“Ruff!”);  

    }  

}  

public class SpeakableAnimal extends Animal  

{  

    public void Speak()  

    {  

        // To be overloaded  

    }  

}  

public class Cat extends SpeakableAnimal  

{  

    public void Speak()  

    {  

        System.out.println(“Meow!”);  

    }  

}  

Movie Clips in Flash do not follow the exact same idea of polymorphism. Flash has an alternative viewpoint in objected oriented perspectives at this point. Movie Clips follow composition rather than inheritance and polymorphism. While MovieClips inherit actions from its parent Movie Clips, the parent is not ideologically the same as a super class in Java. A movie clip does not extend its parent; its parent composes of the movie clip. A Car movie clip will compose of an Engine which will have access to actionscript functions TurnOn()or Drive() defined in Car, but design-wise, Engine does not extend Car. Instead, Car has an Engine. This is where Flash’s attempt of visualizing object oriented programming starts to break down.

Flash also does not visually represent the concept of encapsulation. Encapsulation is the idea that the implementation of an action is not accessible. When a person is asked “What would be one word you would use to describe yourself” during a job interview, a thought process happens in the interviewee’s mind. What the process is the interviewer does not know; however, a one result is outputted to the interviewer by the interviewee. Since the interviewer cannot read minds, the thought process of the interviewee is considered encapsulated. In Java, classes, methods, and properties can be declared public or private. If the attribute is private, then it is used primarily for internal processes. An example could be finding the distance between two points on a two dimensional plane.


public void FindDistance(double x1, double y1, double x2, double y2)  

{  

    return Math.sqrt(Square(y1-y2)+Square(x1-x2));  

}  

private void Square(double n)  

{  

    return n*n;  

}  

FindDistance is a method that a user may use in their program, but the user does not know (or need to know) how that method works. The Square method is actually used by the FindDistance method, but since the user is not allowed and does not need to use the Square method, Square is declared as a private method.

Where OO programming loses its power is when describing abstract objects. For example, feelings and emotions cannot be developed easily. Love or Frustration can extend Feeling; however feelings are not necessarily objects because the concept of an object is arguably something tangible. Because Flash assumes all Movie Clips to be tangible, it is a much easier platform to develop on since positioning objects on the screen is much easier than in Java. In Java and in most programming languages, coordinates on a plane must be defined. In Flash, objects can simply be pasted on certain spots on the screen and the coordinates are automatically set into the objects.

Nevertheless, OO programming is overall a powerful language that allows programmers to design a system before actually coding a design. Especially in Flash, programmers can worry about designing a system rather than mulling over syntax. In Flash that system can be graphically represented, in Java that system can be programmatically represented, and in a designers mind that system can be ideologically represented.