dcsimg
A Flash Developer Resource Site

Results 1 to 8 of 8

Thread: OOP - FAQs, Resources & Best Practices

  1. #1
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668

    OOP - FAQs, Resources & Best Practices

    So a while back, this thread was started:
    http://board.flashkit.com/board/show...93#post3801593

    In response to it, this thread (as in the one you are reading) was started.

    Purpose:
    The purpose of this thread is to provide resources, tips and best practices for those interested in learning more about Object Oriented Programming (henceforth OOP).

    Mostly we want to focus on OOP in relationship to ActionScript, but references to general OOP best practices are welcome as well.

    Expectations:
    People are going to differ as to what they regard as best practices. So what you are going to get are a collection of opinions on best practices. The thread is by no means meant to be gospel.

    If you are referencing some external resource or book please provide a reference or link.

    Hopefully we will have enough experience collectively to make this a useful thread.

    So let's kick it off:

    Resources: (Here is where I go/ I will add more to this later.)

    General OOP:
    Wikiversity School of computer Science:
    http://en.wikiversity.org/wiki/Topic...ed_Programming


    OOP in a Nutshell (for which I may be accused of being a nut):
    So this is meant to be a very basic introduction, so I am going to be abstract (something those of you familiar with OOP should know the benefits of, so go easy on me).

    Basically put, Objects are related pieces of code in a specified syntax that perform a set of related tasks. Objects are created by creating class files (in AS these are external ActionScript files). If you have done even simple coding in Flash, you have probably done something like:

    var myVariable = new MovieClip();

    In this case we have created a variable myVariable that is an instance of the MovieClip object. We know this because of the new key word. When you use the new keyword you are creating and instance of an object. So what exactly go created? Well take a look at (assuming you are on a Windows Machine with Flash 8) C:\Program Files\Macromedia\Flash 8\en\First Run\Classes\FP8\MovieClip.as. , BUT DON’T EDIT IT. Notice it is more or less a collection of variables and functions (in this case mostly abstract methods, but more on that in a later post)

    So why do this, well I can create multiple instances of a movie clip from the same AS file without having to reproduce the code in that file. All instances of this object will have the same variables (aka properties) and functions (aka methods). Once I have multiple instances of a class (aka object) . I can then apply different properties (e.g., set different alpha levels) and call specific behaviors (via methods) for each instance. I can do this because of the design of the MovieClip class. Basically, the MovieClip class defines all of the properties and behaviors expected of a MovieClip. Once I have created and instance of one, I can then set those properties and call the behaviors for each instance of that object.

    So what does a class look like?
    Well you can take a look the classes in C:\Program Files\Macromedia\Flash 8\en\First Run\Classes (Again DON’T EDIT them). These are the basic classes that come with Flash and these are actually what you are calling when you use that new keyword (there’s more to it, but we will get to that in a later post).

    The basic syntax of a class is:

    AS 2.0: File Name would Be ClassName.as
    class ClassName {

    function ClassName(){

    }
    }

    AS 3.0 File name would be ClassName.as (and located in foldername under the root class path, more on this in some later post as well)

    package foldername {
    class ClassName{
    function Classname(){

    }
    }
    }

    Few things to note and then I will sign off for this post:

    The name of the AS file, the class name and the constructor function name (the one I bothered to write out in the examples - this can be one of many functions) must all match. These will also match how you use the keyword new. So for these examples you would create an instance by:

    var myVar = new ClassName();

    which actually ends up calling the constructor method. By having all those names match, Flash knows what file to refer to and what method to call.

    OK I know that was really abstract (and long) and I left a bunch of things out (like data typing and what a class that actually does something looks like), but hopefully this will be the first post of many.

    Bye for now and feel free to contribute.
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


  2. #2
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668

    Dissecting a Class

    So in the last post we looked at some of the very basic things about AS classes. In this post I am going to go a bit further and take a look at an example of basic class.

    So in the last post we examined basic class structure such as (examples in this post are AS 2.0 syntax)

    class SomeClass {
    function SomeClass(){

    }
    }

    This is as simple as a class can get and this class would not actually do anything. So lets take a look at a class that actually does something (all be it something useless and simple)

    The following would go in an external actionscript file named Person.as. For simplicity sake it would be saved in the same folder as the FLA (setting up class paths will be in another post. For a primer on setting up class paths see http://www.flash-mx.com/flash/actionscript_lott2.cfm. Look here is nothing happens when you test the following. I had to tweek the class path in flash 8 to get this to run).

    class Person {
    // example instance variable
    var _myName:String;
    //constructor function
    function Person(myName:String) {
    _myName = myName;
    trace("New Person");
    }
    //example method
    function sayHello() {
    trace("Hello, my name is "+_myName);
    }
    }

    Then in Flash use the following code on an actions layer in the first frame:

    var person = new Person("Bill");
    person.sayHello();

    When you test the movie, you should see the following in the output window:
    New Person
    Hello, my name is Bill

    Here we saw the use of the keyword new followed by the name of the function and in this example we passed a string as the parameter (myName:String). The constructor (the function with the same name as the class and the AS file) is automatically called and executes any code in its body. In this case, it is setting an instance variable _myName (a standard coding convention is to place an underscore in front of instance variables to avoid naming conflicts).

    The next line:
    person.sayHello();

    calls the sayHello() function of the person instance which causes the following function in the class file to execute:

    function sayHello() {
    trace("Hello, my name is "+_myName);
    }

    so we have done several things. First we created an instance of the Person Object (class) and in doing so we set the instance variable _myName to the value passed to the constructor function. Then we called the sayHello method.

    Now that we have this basic class set up, we can create multiple instances. For example:

    var bill = new Person("Bill");
    bill.sayHello();

    var jane = new Person("Jane");
    jane.sayHello();

    var sam = new Person("Sam");
    sam.sayHello();

    Would output:

    New Person
    Hello, my name is Bill
    New Person
    Hello, my name is Jane
    New Person
    Hello, my name is Sam

    So here we can see that with the same class (object) we can assign different properties and call methods on several instance of the same class which all originate from the same AS file (object/class).

    That's all for now.
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


  3. #3
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668

    OOP Basics

    Well now that I have posted some basic examples, I am starting to realize that I have been leaving out some vary basic concepts thus far for the sake of simplicity. So let's take a moment and back track (this should have probably been the first post, but hey - it is a work in progress).

    Most of the following can be found in "Object-Oriented Programming for Flash 8" by Peter Elst and Todd Yard with Sas Jacobs and William Drol published by firendsof ED. (No I don't get royalties I just think the original author's should get credit for their work)

    First thing. I was a bit to causal about using class and object interchangeably.

    Classes and Objects

    According to the previously mentioned book, the relation ship between a class and an object is like that of the relation ship between a a blue print and a house. The blue print is not the house itself (nor can you do anything with it, other than use it to build a house), it is only the specification for what the house needs to provide in terms of structure and function. A house would be the object. It is the manifestation of the specification. You could also build several houses from the same blue print. So, the houses could be thought of as instances of the blue print. Hence in OOP objects are often referred to as class instances.

    OK so that was the first thing I was a bit unclear on. There were other things I just left out(such as data typing, but that shall come later, for now more basics).

    Properties
    Properties allows objects to have unique qualities. In the example in the last post we assigned a unique name to several instances. Properties are generally held in instance variables.

    class Person {
    //this is an instance variable and hence a property;
    private var _myName:String;

    function Person (n:String){
    _myName = n;
    }
    }

    In Flash:
    //same class two instances with _myName property set to two distinct values
    var personOne = new Person("Bill");
    var personTwo = new Person("Jill");

    Encapsulation
    Encapsulation is about hiding the inner workings of how classes accomplish things. So good encapsulation is worthy of its own post, but as a basic idea,
    a person who will end up using a class should not have to know anything about what the code inside the class looks like. All they should have to know is what the public (more on that later to, for now just think of it as the methods the user can call) methods are, what data they have to pass to them, and what data or behavior they should expect to get when calling the method. How the method does what it does is of no concern to the end user. How the methods work is the concern of the person creating the class and if they design it well then the end user should not have to know anything about the internal workings of the class to be able to use it. (least thats the theory)

    and finally for this post ...

    Inheritance
    Ok I will be honest, this topic could (and does) span chapters or books. Boiling this down to a paragraph is going to be messy. But here we go.

    Simply put inheritances allows us to reuse code from other classes in new classes. When one class inherits from another (with some qualifications, this works differently in different languages), the new class inherits (can use or has) all of the methods and properties of the class it inherits from. So lets say we have:

    class Ball{
    //this is a property
    _size:Number
    function Ball(s:Number){
    _size = s
    }
    //most balls bounce
    function bounce(){
    //code that makes the ball bounce
    }
    }

    class BasketBall extends Ball{

    function BasketBall(s:Number){
    super(s);
    }

    }

    in Flash:
    var bb = new BasketBall(5);
    bb.bounce();

    OK the short version of what we just did. Class basket ball inherits from class ball (that is what the extends keyword does). This mean that we can call the bounce function that is defined class ball since basketball inherits from ball. We did not have to redefine bounce (unless we want to, but thats overiding and thats another post again) in any class that inherits from ball.

    OK so, again I am still being very basic and leaving some things out for simplicity sake, but we are moving along.
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


  4. #4
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668

    Data Typing

    Ok so in some of my examples you may remember seeing some thing like:

    var _myName:String;

    This is an example of data typing. Simply put with the above syntax, if I try to assign anything other than a string value to that variable, the compiler will throw an error. So if we:

    //declare a variable that can only hold a string
    var someString:String;

    someString ="Hello" //ok
    someString = 5 //error 5 is not a string
    someString = "5" //this is ok since 5 in this case is the string five and not the number 5 since it is " "'s.

    So why do this. OK well take the following situation:

    //declare some untyped variables that can hold anything
    var holdsAnything1 = "2";
    var holdsAnything2 = "5";

    var total = holdsAnything1 + holdsAnything2;
    trace (total);

    rather than producing 7 this would trace the string 25 (in the context of string, the + sign joins to strings together, in fact in testing this, you can actually leave the quotes off of either the 2 or the 5 and you will still get 25, it is not until you take the quotes off both that you get 7, least in flash 8). Point being what is you inadvertently assign the wrong type of data to a variable that should only hold a certain type. How would you figure out where the assignment went wrong? Well you could start just looking through all of your code........ or use typing as that will throw an error at the point were the assignment goes wrong.

    //note we could have used the same names from the above example, but since I have been giving them names related to the current point, I will continue to do so. The important part is the :Type
    var mustBeNumber1:Number = 2;
    var mustBeNumber2:Number = 5;

    var total:Number = mustBeNumber1 + mustBeNumber2;
    trace (total);

    With the above setup, the compiler will throw an error at the point we try to assign the undesirable value to the specific variable and will point us to the line on which it occurred.

    Other benefits of typing include:
    (See: http://www.oman3d.com/tutorials/flash/variables_bc/)
    One should not underestimate the benefits of strict data types, they do not only prevent you from assigning an incompatible data type and make error correction much easier, but they also make your code much easier to read because as the intended purposes of the variables that you create become clearer and easier to follow. A great other benefit of using Strict Data Typing is that variables to which this feature is enabled activate ActionScript quick reference code hints that pop-up when the variable name is written in ActionScript.
    And finally, this will also work with you own custom classes that you create. So from out previous examples. I could:

    //create a variable to hold an instance of a class I have created:

    var someBody:Person = new Person("Typed Variable");

    with the :Person syntax, I can only ever hold an instance of the person class that I created in that variable.


    Now just as one final note as there can be endless debate back and forth as to whether typing is useful (some people like, some hate it, and there are those in between). There are occasions where you may want a variable that can hold multiple types of data. And if that is what you want and have designed for it, then that is equally as valid.


    For an indepth look at the topic of typing see:
    http://en.wikipedia.org/wiki/Type_system
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


  5. #5
    Senior Member calmchess's Avatar
    Join Date
    Sep 2006
    Location
    Earth
    Posts
    2,588
    I have request .....I'd like to learn more about event handlers with oop because I currently have a oop script that extends an input text field or a dynamic text field its an chat application with a submit button but I can't figure out for the life of me how to make it submit by pressing the enter key instead of always having to click on the submit button........I'd love a nice tutorial on event handlers particularly keyboard button press for specific keys using oop....to be clear the event handlers would be part of the oop .as file.

  6. #6
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668
    I think in that situation you are actually going to end up using the Key listener.

    http://www.adobe.com/support/flash/a...ionary394.html

    TextField only seem to have two built in events onChange and onScroll.


    Hopefully some other may chime in on this one.

    Quote Originally Posted by calmchess
    I have request .....I'd like to learn more about event handlers with oop because I currently have a oop script that extends an input text field or a dynamic text field its an chat application with a submit button but I can't figure out for the life of me how to make it submit by pressing the enter key instead of always having to click on the submit button........I'd love a nice tutorial on event handlers particularly keyboard button press for specific keys using oop....to be clear the event handlers would be part of the oop .as file.
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


  7. #7
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668
    calmchess, not sure what your particular set up looks like, but something like this might work(you can ignore the general class structure, as it is only there for contextual purposes. The important stuff is the key listener and the onKeyDown function):

    import TextField.as;
    class ChatTextField extends TextField{
    private var tf:TextField;
    function ChatTextField (tf:TextField){
    this.tf = tf;
    trace(this.tf)
    Key.addListener(this);
    }
    function onKeyDown(evt:Object){
    if (Key.getCode() == Key.ENTER)
    trace("Enter key pressed ");
    }
    }
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


  8. #8
    OOP is one letter from OOPS kortex's Avatar
    Join Date
    Aug 2005
    Location
    New Hope, PA
    Posts
    2,668

    EventHandlers - EventListeners

    Event Listeners:

    Ok so most of you are probably familiar with doing some thing like:
    Code:
    on (release){
    //do something
    }
    OR
    Code:
    myButton_btn.onRelease = function () {
    //do something 
    }
    OR

    Code:
    function doSomething(){
    // go ahead guess what goes here
    }
    
    myButton_btn.onRelease = doSomething;
    All of the above are simple examples of using an event (in this case the on release event) to trigger some code. You can even get a bit more complex by doing the following:

    Code:
    var iHearYou:Object = new Object(); 
    
    iHearYou.change = function (evtObj:Object){
    //do something
    }
    
    myTextInput.addEventListener(“change”, iHearYou)
    In the above example we actually created our own object and assigned a function named change. Then we added and event listener to a text input component that registers our object to listen for the change event. Hence every time the text is changed in our text input we have added the listener to, the change function in our object will be executed. This example illustrates several important things.

    1. A listener is actually an object with specific functions that get executed when an event is broadcast. Generally the function name matches the event to be listed to.
    2. The object that the listener is added to must dispatch the specified event. If it does not, the listener will never be triggered.




    So what are the benefits of using event listeners as objects?

    Event listeners provide a more flexible event handling model than change handlers in Flash MX. For example, a listener object can receive events from several components; likewise, a component can broadcast a single event to multiple listeners. For more information about handling component events, see About Component Events in the Using Components Guide.
    (From: http://www.adobe.com/devnet/flash/ar...04_print.html)

    So how does this work with classes? Well let's look as some examples. For this we will use two custom made classes (you can download these to play with them, just remember to set up you class path – see previous post for link to instructions for doing this):
    Code:
    class Ear
    {
    	//I am a bit nosy and like to listen in
    	function onKeyDown ()
    	{
    		trace ("I hear you pressed key number " + Key.getAscii () + " pressed");
    	}
    	function change (evtObj : Object)
    	{
    		trace ("Lisenting to " + evtObj.target._name + " type." )
    	}
    	function focusOut(evtObj:Object){
    		trace ( "I hear that " + evtObj.target._name + " says " + evtObj.target.text )
    	}
    }
    
    class Mouth
    {
    	//I like to gossip.
    	function onKeyDown()
    	{
    		trace ("Let's talk about key number " + Key.getAscii() );
    	}
    	function change (evtObj : Object)
    	{
    		trace ( evtObj.target._name + " is typing." )
    	}
    	function focusOut(evtObj:Object){
    		trace ( evtObj.target._name + " says " + evtObj.target.text )
    	}
    }
    Take notice of the following with the above two classes:
    1. Both classes have exactly the same functions in terms of names, but trace different things. (i.e. in different listeners we can have the same function name, but do different things with them)
    2. The function names must match the events they listen for. This will vary based on the object that you will register the listener to. In this case we will be using the Key object and TextInput components as examples.
    3. Listener functions can receive the object that triggered them as a parameter, hence I can access the properties of the triggering object (see change and focusOut functions in example classes). Hence if I wanted to, I could vary my code based on the object that triggered it.

    So now we have out classes: In Flash we can now:
    Code:
    var nosy:Ear = new Ear(); 
    var chatty:Mouth = new Mouth(); 
    Key.addListener(nosy);
    Key.addListener(chatty);
    bob.addEventListener("change", nosy); 
    bob.addEventListener("focusOut", nosy); 
    bob.addEventListener("change", chatty); 
    bob.addEventListener("focusOut", chatty); 
    jack.addEventListener("change", nosy); 
    jack.addEventListener("focusOut", nosy); 
    jack.addEventListener("change", chatty); 
    jack.addEventListener("focusOut", chatty); 
    jill.addEventListener("change", nosy); 
    jill.addEventListener("focusOut", nosy); 
    jill.addEventListener("change", chatty); 
    jill.addEventListener("focusOut", chatty);
    While the above could look a bit messy, what it is meant to illustrate is the following:
    1. You can register multiple objects to the same listener.
    2. You can register multiple listeners to the same object.

    So basically I can trigger multiple functions in different objects all with the same event, or multiple objects can trigger the same function. I don’t have to rewrite it for each object.

    Since this is getting a bit long, if you want to see how this works, download the attached files and play with it by commenting out some of the lines in the Flash code above to see how what gets traced out changes.

    See also:
    http://livedocs.macromedia.com/flash...=00001375.html
    Attached Files Attached Files
    Jeremy Wischusen
    Flash - Flex - LAMP - Web Developer Purple Inc
    AS OOP FAQ-Best Practices Thread | Flashkit OOP Tutorials | Purple Inc (day job) | Blog


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center