Friday, January 14, 2011

What is OOP and Why Should I Care?

What is object-oriented programming (OOP)?

If you Google this question, you will get hundreds of answers. Here is my answer along with an anecdotal description.
Unlike earlier programming styles,
Object-oriented programming is a programming style that mimics the way most people think and work .
An anecdotal description
If you have ever assembled a child's playscape in your back yard, this scenario should sound familiar to you.
When you opened the large boxes containing the playscape, hundreds of objects spilled onto the ground. Those objects may have consisted of braces, chains, swing seats, slides, screws, nuts, bolts, washers, climbing ropes, ladder rungs, and other assorted objects.
Atomic and non-atomic objects
I will refer to the kind of object that I have described in the above list as atomic objects. What I mean by that is that they can't be easily subdivided into smaller objects.
If you were lucky, some of the objects in the box may not have been atomic objects. Instead they may have been pre-assembled arrangements of atomic objects such as a climbing net composed of individual ropes tied together to form a net.
Your job - assemble the objects
Your job was to assemble those hundreds of atomic and non-atomic objects into a final object which you proudly referred to as "The Playscape."
Objects working together
It has been said that a successful object-oriented program consists of a bunch of cooperating software objects working together to achieve a specified behavior. The overall behavior of the program is the combination of behaviors of the individual objects. For example, some objects may acquire input data, other objects may compute and produce output data, while other objects may display the output data.
It could also be said that a playscape consists of a bunch of hardware objects working together to achieve a specified behavior. The overall behavior of the playscape is the combination of behaviors of the individual objects. For example, the behavior of some of the braces is to stand strong and not bend or break, while the behavior of a swing is to be flexible and move in a prescribed way.
Creating a model
One of the tasks of an object-oriented programmer is to assemble software objects into a model that often represents something that exists in the real world. For a very visual example, you might be asked to create an advertising web page showing an animated software model of the playscape that you assembled in your back yard. With the playscape, you were simply required to assemble the existing hardware objects. However, in the object-oriented programming world, you must do more than just assemble objects.
Objects must be designed and manufactured
Getting back to the playscape, every one of the objects for the playscape was manufactured before being shipped to you. Even before that, each object was designed by someone and a set of manufacturing drawings was probably created so that the object could be mass produced in a high-volume manufacturing facility.
A class is analogous to manufacturing drawings
In OOP, there is a direct analogy to the manufacturing drawings of the hardware world. We call it a class . A class documents the specifications for the construction of a particular type of software object.
A large library of classes
As an object-oriented programmer, you will typically have access to a large library of existing classes from which you can construct different types of software objects, such as buttons, sliders, etc. In addition, you will often need to design and define new classes from which you can construct new types of objects.

Why should I care?

Although ActionScript and Flex provide a large class library from which you can construct objects (components) , you will probably need to create new custom components from time to time as well.
ActionScript is usually required
Flex/MXML can be used to create simple custom components but ActionScript is often needed to cause those components to have more interesting behavior.
Sometimes you can embed or include non-OO ActionScript code in a Flex MXML file to achieve the desired behavior. Often, however, you will need to create your new component almost entirely in ActionScript. You will need to understand OOP in order to do that.
Start from scratch or extend an existing component class
An understanding of OOP is particularly important if you need to create a new component from scratch or create a new component by modifying the appearance and/or behavior of a component for which a class already exists.
I will provide an example of a new custom component that extends an existing component later in this lesson.
Therefore, if you plan to create rich internet applications, games, or iPhone applications using ActionScript, you will often need to understand OOP in order to create custom components that your clients find interesting.

General background information

Some languages such as C do not readily support OOP. Other languages such as C++ and ActionScript support OOP, but don't require you to use the object-oriented features of the language. Still other languages such as Java and C# require you to program using OOP techniques.
OOP is not enforced
Because ActionScript does not enforce a requirement for your code to be object oriented (OO) , it is possible to learn to use major aspects of ActionScript without ever learning to use the object-oriented features. This approach simply requires you to learn how to use the rudimentary aspects of the language.
The real challenge
The real challenge to becoming an ActionScript programmer is not simply to learn the rudimentary aspects of the language. The real challenge lies in:
  • Learning to productively use the large class library provided as part of the software development kit.
  • Learning to design and define new classes when needed.
  • Learning to design and program in the object-oriented paradigm.
Learn the library gradually
The first of these challenges can be met on a gradual basis. In other words, it is not necessary to memorize the entire class library to produce useful OO programs. However, it is necessary to learn how to use the library documentation to find what you need.
Some things can't be learned gradually
The remaining two challenges cannot easily be met on a gradual basis. Many aspects of OOP must be understood before a programmer can successfully write OO programs

A slightly more technical description of OOP

An introductory description of OOP can be based on the guideline in Figure 1.
Figure 1: Guideline for OOP.
Guideline for OOP.
The solution to the problem should resemble the problem, and observers of the solution should be able to recognize the problem without necessarily knowing about it in advance.
For example, an OO program that deals with banking transactions should be recognizable on the basis of the objects that it uses, such as deposit objects, withdrawal objects, account objects, etc.
Flex is a good example
Many "application frameworks" are written according to the OOP paradigm. Important among these is Adobe's Flex, which can be used to simplify the development of the graphical user interface (GUI) portions of ActionScript programs.
Flex makes it possible to use uncomplicated XML syntax to access and use the ActionScript class library. Adobe's Flash Builder 4 makes the process even more straightforward by providing a largely drag-and-drop visual development environment for creating the GUI portion of ActionScript programs.
All of the components that are available in Flex are objects created from classes in the ActionScript library. Those classes have names like Button RadioButton , and NumericStepper (see Figure 2) .
Three important concepts
Any object-oriented language must support three very important concepts:
  • Encapsulation,
  • Inheritance,
  • Polymorphism.
We use these three concepts extensively as we attempt to model the real-world problems that we are trying to solve with our object-oriented programs. I will provide brief descriptions of these concepts in the remainder of this lesson and explain them in detail in future lessons.

Encapsulation example

Consider the steering mechanism of a car as a real-world example of encapsulation. During the past eighty years or so, the steering mechanism for the automobile has evolved into an objectin the OOP sense.
Only the interface is exposed
In particular, most of us know how to use the steering mechanism of an automobile without having any idea whatsoever how it is implemented. All most of us care about is the interface ,which we often refer to as a steering wheel. We know that if we turn the steering wheel clockwise, the car will turn to the right, and if we turn it counterclockwise, the car will turn to the left.
How is it implemented?
Most of us don't know, and don't really care, how the steering mechanism is actually implemented "under the hood." In fact, there are probably a number of different implementations for various brands and models of automobiles. Regardless of the brand and model, however, the human interface is pretty much the same. Clockwise turns to the right, counterclockwise turns to the left.
As in the steering mechanism for a car, a common approach in OOP is to "hide the implementation" and "expose the interface" through encapsulation.

Inheritance example

Another important aspect of OOP is inheritance . Let's form an analogy with the teenager who is building a hotrod. That teenager doesn't normally start with a large chunk of steel and carve an engine out of it. Rather, the teenager will usually start with an existing engine and make improvements to it.
In OOP lingo, that teenager extends the existing engine, derives from the existing engine, inherits from the existing engine, or subclasses the existing engine (depending on which author is describing the process) .
Just like in "souping up" an engine for a hotrod, a very common practice in OOP is to create new improved objects by extending existing class definitions.
Reuse, don't reinvent
One of the major arguments in favor of OOP is that it provides a formal mechanism that encourages the reuse of existing programming elements. One of the mottos of OOP is "reuse, don't reinvent."

Polymorphism example

A third important aspect of OOP is polymorphism . This is a Greek word meaning something like one name, many forms . This is a little more difficult to explain in non-programming terminology. However, we will stretch our imagination a little and say that polymorphism is somewhat akin to the automatic transmission in your car. In my Honda, for example, the automatic transmission has four different methods or functions known collectively as Drive (in addition to the functions of Reverse, Park, and Neutral) .
Select Drive to go forward
As an operator of the automobile, I simply select Drive (meaning go forward) . Depending on various conditions at runtime , the automatic transmission system decides which version of theDrive function to use in every specific situation. The specific version of the function that is used is based on the current conditions (speed, incline, etc.) . This is somewhat analogous to what we will refer to in a subsequent tutorial lesson as runtime polymorphism .

Object-oriented programming vocabulary

OOP involves a whole new vocabulary (or jargon) which is different from or supplemental to the vocabulary of procedural programming.
For example the object-oriented programmer defines an abstract data type by encapsulating its implementation and its interface into a class .
One or more instances of the class can then be instantiated .
An instance of a class is known as an object .
Every object has state and behavior where the state is determined by the current values stored in the object's instance variables and the behavior is determined by the instance methods of the class from which the object was instantiated .
Inherited abstract data types are derived classes or subclasses of base classes or super classes . We extend super classes to create subclasses .
Within the program, the code instantiates objects (creates instances of classes) and sends messages to the objects by invoking or calling the class's methods (or member functions) .
If a program is "object oriented", it uses encapsulation inheritance , and polymorphism . It defines abstract data types encapsulates those abstract data types into classes instantiates objects , and sends messages to the objects .
To make things even more confusing, almost every item or action used in the OOP jargon has evolved to be described by several different terms. For example, we can cause an object tochange its state by sending it a message calling its methods , or calling its member functions . The term being used often depends on the author who wrote the specific book that you happen to be reading at the time.
Hopefully most of this terminology will become clear as we pursue these lessons.

Sample code

We have reached the point in this discussion where I should provide some examples of ActionScript 3 class definitions so that you can get a preview of what lies ahead.

A simple class named MyClass

The code beginning with the word public in Listing 1 is the definition of a very simple class named MyClass . I don't expect this code to mean much to you at this point. Suffice it to say that an object of this class is a new GUI component consisting of a Button object, a RadioButton object, and a NumericStepper object, all contained in a VBox object.

LISTING 1: Class file named MyClass.as.

package Classes{
  import mx.containers.VBox;
  import mx.controls.Button;
  import mx.controls.RadioButton;
  import mx.controls.NumericStepper;
  
  public class MyClass extends VBox{
    //Constructor follows
    public function MyClass(){
      addChild(new Button());
      addChild(new RadioButton());
      addChild(new NumericStepper());
      setStyle("backgroundColor",0xFFFF00);
    }//end constructor
  }//end class
}//end package
A new data type
The definition of the class creates a new data type, which is unknown to the compiler until it is defined by the programmer.
Two instances (objects) of the class named MyClass
Two objects of the new class named MyClass are shown in Figure 2. You should be able to spot the Button object (rectangular) , the RadioButton object (circular) , and theNumericStepper object in each of the two MyClass objects.
Figure 2: Two objects of the class named MyClass.
Two objects of the class named MyClass.
Missing image.
A yellow background
Normally you can't see a VBox object. You can only see the components that it contains. However, I included code in Listing 1 to set the background style of the VBox object to yellow to make it possible for you to visually separate the two new custom objects in Figure 2.
The Flex MXML file
Listing 2 shows the Flex file that was used to instantiate the two objects of the class named MyClass and to display them in the Flash Player window in a browser.

LISTING 2: Flex file named SimpleClass01.mxml.

<?xml version="1.0" encoding="utf-8"?>

<!--SimpleClass01 -->

<mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:classes="Classes.*">

    <classes:MyClass />
    <classes:MyClass />
    
</mx:Application>
The two lines of code beginning with the words classes in Listing 2 cause the two new objects to be instantiated and displayed.

Another custom component - NumericTextAreaA

One of the standard Flex components is named TextArea . This component is an object of the ActionScript class having the same name.
A custom component that extends TextArea
As an example of creating a new custom component that extends an existing class, I will present and discuss a new custom component that extends the TextArea class. The new class is named NumericTextAreaA.
An object of the NumericTextAreaA class behaves just like an object of the standard TextArea class except that the new component will only accept numeric characters, the space character, the backspace character, and the return character. All other characters are rejected when the user attempts to type them into the text area.
An object of the class named NumericTextAreaA
Figure 3 shows the visual manifestation of an object of this class with two lines of numeric and space characters having been entered. (The entry of additional lines of text causes scroll bars to automatically appear.)
Figure 3: An object of the class named NumericTextAreaA.
An object of the class named NumericTextAreaA.
Missing image.
A class definition is probably required
It is possible to create simple custom components by embedding ActionScript code in a Flex MXML file. However, I don't believe that it is possible to create an object with this behavior without defining a new ActionScript class. Even if it is possible, defining a new class is the approach that makes the most sense to me.
The file named NumericTextArea01.mxml
The MXML code beginning with cc in Listing 3 instantiates the object shown in Figure 3.

LISTING 3: The file named NumericTextArea01.mxml.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:cc="CustomClasses.*">
    
    <cc:NumericTextAreaA/>

</mx:Application>
The class definition for NumericTextAreaA
Listing 4 shows the class definition from which the object shown in Figure 3 was instantiated.

LISTING 4: The class definition for NumericTextAreaA.

/*This is a custom component. This class extends the
TextArea class.  It recognizes only the following 
characters:
0, 1, 2, 3, 4, 5, 6, 7, 8,9
space
backspace
return key

The next numeric character is appended onto the end of
the string in the text area regardless of the current
position of the cursor.

The backspace key deletes characters from the end of the
string, one character at a time.
*********************************************************/

package CustomClasses{
    import mx.controls.TextArea;
    import mx.controls.Alert;
    import flash.events.*

    public class NumericTextAreaA extends TextArea{
        private var theText:String = "";
        
        public function NumericTextAreaA(){
            this.addEventListener("keyUp",processKey);
        }//end constructor

        private function processKey(
                                event:KeyboardEvent):void{
            if(event.charCode==48){
                theText+="0";
            }else if(event.charCode==49){
                theText+="1";
            }else if(event.charCode==50){
                theText+="2";
            }else if(event.charCode==51){
                theText+="3";
            }else if(event.charCode==52){
                theText+="4";
            }else if(event.charCode==53){
                theText+="5";
            }else if(event.charCode==54){
                theText+="6";
            }else if(event.charCode==55){
                theText+="7";
            }else if(event.charCode==56){
                theText+="8";
            }else if(event.charCode==57){
                theText+="9";
            }else if(event.charCode==8){//backspace
                theText=
                       theText.substr(0,theText.length-1);
            }else if(event.charCode==32){//space
                theText+=" ";
            }else if(event.charCode==13){//return key
                theText+="\n";
            }//end else

            this.text=theText;
        }//end processKey method
    }//end class
}//end package
May not be familiar code
There may be quite a lot of code in Listing 4 with which you are not familiar. However, it is not my purpose in writing this lesson to get into the details of defining classes in ActionScript, so I won't take the time to explain this code in this lesson. Suffice it to say that Listing 4 checks the character code associated with each keystroke in the text area and rejects all but the numeric characters, the backspace character, the space character, and the return key.
I will explain code like this in detail in future lessons. For now, simply accept this as an example of why you may need to learn OOP in order to advance your career as an ActionScript programmer.
Running the ActionScript program named NumericTextArea01
If you have the Flash Player plug-in (version 9 or later) installed in your browser you should be able to run this program by clicking on NumericTextArea01 .
Enter some alphabetic and numeric text in the white box to see how the GUI component behaves. Click the "Back" button in your browser to return to this page when you are finished experimenting with the component.
If you don't have the proper Flash Player installed, you should be notified of that fact and given an opportunity to download and install the Flash Player plug-in program.

Resources

I will publish a list containing links to ActionScript resources as a separate document. Search for ActionScript Resources in the Connexions search box.

Miscellaneous

NOTE: 

Housekeeping material
  • Module name: What is OOP and Why Should I Care?
  • Files:
    • ActionScript0104\ActionScript0104.htm
    • ActionScript0104\Connexions\ActionScriptXhtml0104.htm

NOTE: 

PDF disclaimer: Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.
-end-

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

java

Popular java Topics