Object Orientation

Here’s another post that I originally wrote way back in 2006, when object oriented development was a newer concept to client-side web applications. Again, this post is still very relevant with Flex, AIR & ActionScript for mobile/web/desktop, so I decided to resurrect it from the old blog archive as well. Enjoy…

Understanding of OOP (Object Oriented Programming) is fundamental in being successful with the Flex framework and being able to get the most out of it. Developers who do not possess a computer science-related background may not be aware of the fundamental concepts that comprise OOP and how to apply them correctly, so here is a quick piece to help you out.

First, object oriented programming is a programming paradigm where your code is organized into logical objects, and each object has properties and methods. Each object contains similar and/or related functionality, and is organized into classes that logically represent and logically organize it’s functionality.

For Example:
Let’s say that we have a class “Automobile”. This class would contain the information and functions necessary for our application to use the Automobile class. We could have a numeric property for the number of wheels, the speed, and the direction (degrees on a compass). This class would also contain methods that control the actions of the Automobile object: accelerate, decelerate(break), turn, start engine, stop engine, etc… Our class would look something like this…

public class Automobile
	public var speed : Number;
	public var direction : Number;
	public var numWheels : Number;
	public function Automobile()
	{ /* constructor */ }
	public function accelerate() : void
	{ /* speed up the automobile */ }
	public function decelerate() : void
	{ /* slow down the automobile */ }
	public function turn( direction : Number ) : void
	{ /* turn the automobile */ }
	public function startEngine() : void
	{ /* start the automobile engine */ }
	public function stopEngine() : void
	{ /* stop the automobile engine */ }

Ok, now that we have a brief explanation of what object oriented programming is, we can get into some more aspects of OOP: inheritance and interfaces.

Inheritance is a way to form new objects based on existing objects. When a class inherits from a base class, the new class extends the functionality of the base class, and can utilize public and protected properties and methods from that base class. Inheritance can be used to create different objects that utilize functions within the base class, so that the child classes all utilize the same code base. Inheritance can be used to extend the functionality of existing objects, and inheritance can also be used to override and/ or change functionality from the base class.

In Actionscript 3, you can access the parent class of your class by using the “super” keyword. For instance, calling the constructor of the parent class would use “super()”, where accessing a method of the parent class would use something like: “super.myMethodName()”. If a property of the parent class is created with public or protected access, you can access that property in the child class directly by the property name (you would use this.propertyName, not super.propertyName).

Now, Lets take our Automobile example and apply object-oriented inheritance. We already have a base Automobile class that covers the basic functionality. We can create child classes that extend the functionality of the Automobile.

public class SportsCar extends Automobile
	public function SportsCar()
	override public function accelerate():void
		/* we can override the accelerate function
		     so that it accelerates faster than the base
		     Automobile */


public class Truck extends Automobile
	public function Truck()
	public function tow() : void
		/* we can add a tow function that
		   allows the Automobile class to tow
		   items. */ 

These classes extend the base functionality of the Automobile class, and therefore are instances of the Automobile class. If we have a function outside of the Automobile class, which takes an automobile as the parameter, both a SportsCar and Truck will work since they are both Automobiles. We could have a function such as the following: If we pass in a Truck Instance, and a SportsCar instance, both will work, and each will use the functionality of their specific class instead of the base Automobile class.

public function race( auto1 : Automobile, auto2 : Automobile ) : void

I’ll get into some more fine-grain details about inheritance later in this post… now, lets move on to interfaces…

Interfaces are slightly different than inheritance. An interface is a set of “rules” which an object must adhere to. The “rules” are actually method signatures that your class must implement. When we define an interface, we define method signatures that are required for classes that implement that interface. There is no actual code in an interface; it simply defines methods that must exist within your class. Your class that implements the interface must implement the code for the actual function. If you have multiple classes that implement an interface, those classes must have the same functions (only the ones required by the interface), but that is where the similarities of the two classes may stop. They could have completely different logic and properties within them… this is where inheritance and interfaces differ. Two objects that inherit from the same base class have a lot in common (properties and methods): two objects that implement the same interface only have those interface method signatures in common.

Let’s now make an Automobile Interface that defines the functions required to create an IAutomobile object (note the “I” stands for “interface”):

public interface IAutomobile
	function accelerate() : void;
	function decelerate() : void;
	function turn( direction : Number ) : void;

We can use the IAutomobile interface to create objects (classes) that behave as Automobile objects. These classes do not necessarily inherit from each other and do not necessarily share any common properties.

public class Car implements IAutomobile
	private var direction:Number;
	private var speed:Number;
	public function turn(direction:Number):void
		this.direction = direction;
	public function decelerate():void
	public function accelerate():void
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas implements="IAutomobile"

			private var direction:Number;
			private var speed:Number;
			public function turn(direction:Number):void
				this.direction = direction;
			public function decellerate():void
			public function accellerate():void

The previous two components both implement the IAutomobile interface, but have nothing else in common. One is simply a class that implements the interface, the other is a mxml component that implements the interface. The mxml component example extends the mx:Canvas component (the same thing could be done by creating an AS class that extends mx.containers.Canvas). Now, lets look at a function similar to the “race” function from earlier…

public function race( auto1 : IAutomobile, auto2 : IAutomobile ) : void

This example will work with either object that I have created because both objects implement the IAutomobile interface. They do not rely upon functions in the class hierarchy, just those that were implemented for this interface. You can also use multiple interfaces on classes that you create. Implementing multiple interfaces basically means that you are adding more required method signatures to your class, and you will have to implement these methods to satisfy each interface.

On the other hand, you cannot inherit from multiple classes. Some programming languages allow for multiple inheritance… ActionScript 3 does not support multiple inheritance (so i’ll stop there).

OK… enough of this rambling… What does this have to do with Flex?
Inheritance and interfaces are used extensively in AS3 to create the flex framework. All flex framework components that are rendered to the screen extend from the UIComponent class. AbstractService, DataSerice or EventDispatcher object implements the IEventDispatcher Interface. You may be using these concepts every day, but weren’t aware of them. Inheritance seems easier to take advanatage of at first… Lets say that you want to create several objects, all of which will have identical functions and variables. It is easy to see that you can create a base class that encapsulates all of the common functionality. You can then create a sub-classes that implement the differing functionality for each class.

When putting these concepts into real-world Flex applications you’ll need to get familiar with the following keywords:

This is used when defining a child class from a parent class.

public class MyImage extends Image

This is used when implementing an interface.

public class MyClass implements MyInterface

Classes and methods implented with “final” cannot be overridden.

final function myFunction() : void

The static keyword is used when creating variables or functions in a class that are specific to the class, not an instance. Static properties and methods do not require variable instantiation to be executed.

public static function myStaticFunction(): void
//to use it call it directly from ClassMyClass.myStaticFunction()

This is used when creating a method or property that can be accessed by any object within the same package (namespace)

internal var foo : String;

This is used when creating a function that overrides another function from a parent class.

override public function myFunction() : void

This is used when creating methods or properties that are only available to the class where it is defined. A private variable cannot be accessed by outside classes or from descendant classes.

private var myPrivateValue : String;

This is used when creating methods or properties that are only available to the class where it is defined and descendant classes. A protected variable cannot be accessed by outside classes.

protected var myProtectedValue : String;

This is used when creating properties and methods that are available to any class.

public var myPublicValue : String;

Flex for Mobile – Device Form Factor Detection

Here’s a quick tip for detecting device form factor (tablet vs phone) within your Flex mobile applications. First, get the stage dimensions for the screen size in pixels, then divide that by the applicationDPI (screen pixel density).  This will give you the approximate size in inches of the device’s screen.   I say “approximate” because the pixel densities are rounded to 160, 240, or 320, depending on the device.    In my code, I make the assumption that if the landscape width is greater than or equal to 5 inches, then its a tablet.  I used view states, but you can also layout components manually.

Check out the code below:

<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009" 
			import mx.core.FlexGlobals;
			import mx.events.ResizeEvent;
			protected function view1_resizeHandler(event:ResizeEvent):void
				var _width : Number = Math.max( stage.stageWidth, stage.stageHeight );
				var _height : Number = Math.min( stage.stageWidth, stage.stageHeight );
				_width = _width / FlexGlobals.topLevelApplication.applicationDPI;
				_height = _height / FlexGlobals.topLevelApplication.applicationDPI;
				//this will resolve to the physical size in inches... 
				//if greater than 5 inches, assume its a tablet
				if ( _width >= 5 )
					currentState = "tablet";
					currentState = "phone";
		<s:State name="tablet" />
		<s:State name="phone" />
	<views:PhoneView includeIn="phone" 
					 width="100%" height="100%" />
	<views:TabletView includeIn="tablet" 
					  width="100%" height="100%" />

This technique will enable you to build applications that tailor their interface to the types of devices where they are being consumed. If you’d like to read more, fellow Adobe Evangelist Michael Chaize also has a great example showing how to combine device form factor and orientation into Flex view states.

Ready For Adobe MAX 2011?

Adobe MAX 2011 is rapidly approaching, are you ready? Next week will bring some exciting announcements, so be sure to watch the MAX Keynotes steamed live online if you aren’t able to be there in person (Monday AND Tuesday). Definitely do not miss them.

Adobe MAX 2011

For those of you who will be able to attend, don’t forget to get the MAX companion application, available for iOS and Android at http://max.adobe.com/companion/. The MAX Companion is an application that enables MAX attendees to check their session schedules and access general information about the MAX 2011 conference being held October 1-5, 2011 in Los Angeles, CA.

MAX Companion

If you are interested in HTML5, or Flex/AIR for mobile, also don’t forget to stop by and check out my labs & sessions:

  • Create beautiful, immersive content and applications with HTML5 and CSS3
    Sunday, October 2, 9:00 a.m. – 5:00 p.m.

    Stay up to date on the latest developments in HTML, CSS, and javascript. Learn how to use HTML5 to add interactivity, motion, and video to the web. This lab will start with the fundamentals of HTML5 and how it can be used today for both designers and developers. Get tips, tricks, and best practices from experts, while learning how to apply Adobe’s tools into your evolving workflow. Discover what can be done with next-generation web standards to create powerfully engaging websites that can transcend screens of all sizes.

  • Multi-Device Best Practices Using Flex 4.5 and Adobe AIR for mobile
    Monday, October 3, 5:00 p.m. – 6:30 p.m.
    Tuesday, October 4, 12:30 p.m. – 2:00 p.m.

    Learn techniques and lessons from real-world mobile application development, including UI/skinning approaches, custom components, platform integration, application architecture, and device dependent considerations.

  • Practical Mobile Development with Flex and Adobe AIR
    Wednesday, October 5, 8:00 a.m. – 9:00 a.m.

    Learn techniques and lessons from real-world mobile application development, including UI/skinning approaches, custom components, platform integration, application architecture, and device dependent considerations. You’ll come away better prepared to embrace the industry-shifting paradigm change that mobile development promises.

Visualizing Complex Enterprise Data in a Tablet World

My recent Developer Deep Dive webinar “Visualizing Complex Enterprise Data in a Tablet World” is now available on the Adobe Enterprise Developers Portal.   In this webinar, I walk through the fundamentals of a rich, enterprise-data driven mobile experience, powered by Flex, AIR, LCDS, & LCCS.

Take a look at this short clip to get a feel for what’s covered in this webinar…

(Mobile Maps powered by ESRI)

Now, go view the webinar in its entirety to check out how this experience was built:

Grab the source code here:

Flex & Flash Builder 4.6

Not only were Flash Player 11 & Air 3 announced yesterday, but also the arrival of Flex & Flash Buidler 4.6. Flex & Flash Buidler 4.6 bring forth a new benchmark in performance, as well as a new & enhanced set of tools for developing mobile, desktop, and web applications. Bonus!!! – Flash Builder 4.6 will be a FREE update to all Flash Builder 4.5 customers.

First, let’s talk performance:

Adobe remains focused on performance and in Flex 4.6 we’ve made considerable improvements. Many key performance optimizations were introduced, giving mobile applications the native feel you expect. Simply repackaging, an existing Flex mobile application with Flex 4.6 can yield up to a 50% performance gain. Creating a new application in Flex 4.6 will deliver near-native performance with the superior customization you expect from Flex.

If that wasn’t reason enough alone, let’s talk about the framework:

  • SplitViewNavigator – A new top-level application component specifically designed for the tablet experience. With only a few lines of code, manage the layout of multiple views and have them adapt automatically based on device orientation.
  • CallOutButton – A versatile component that pops over existing content and can contain text, components or even entire views.
  • SpinnerList – This popular tablet component is an adaption of the existing List component. It not only has a new look, but also gives options like recirculating content and a position based selection model.
  • DateSpinner – A highly flexible component that is not only locale-aware, but provides multiple out-of-the-box configurations to fit most date/time entry needs.
  • Text Enhancements – Flex 4.6 solves the problem of cross-device text input. Flex exposes the native text-editing controls on EVERY platform—this enables the developer to customize the keyboard and the user to experience the native UI of common operations like selection, copy/paste and spelling checking.
  • ToggleSwitch
    This simple and much-requested control is now available in Flex 4.6.

Don’t forget tooling:

  • Native Extensions – Enable your applications to complement AIR apps with native code functionality.
  • Captive Runtime – Package the AIR runtime with your application in a native install file. No longer will you have a 3rd party dependency.

Excited yet? Go sign up for the prerelease program today!