You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Java IoT, Adobe Flex

ColdFusion: Article

Object-Oriented Programming in ActionScript 3 vs Java

Programming with and without Interfaces in Flex

From Farata Systems blog

Several years ago I wrote an article on using abstract classses and interfaces in Java . Back than I was absolutely sure that writing object-oriented code is a must. These days, I'm using yet another  language called ActionScript 3 (AS3), which supports all OOP  paraphenalia plus has provisions for dynamic data types. This article illustrates  my up to date vision of OOP with and without interfaces. OK, let's go.

You know the drill: a language is called object-oriented if it supports inheritance, encapsulation and polymorphism. The first two notions can be easily defined:

•  Inheritance allows you to design a class by deriving it from an existing one. This feature allows you to reuse existing code without doing copy and paste. AS3 provides the keyword extends for declaring class inheritance, for example:

package com.theriabook.oop{
   public class Person {
     var name:String;

package com.theriabook.oop{
   public class Consultant extends Person{
       var dailyRate:Number;

package com.theriabook.oop{
   public class Employee extends Person{
       var salary:Number;

Listing 1. The ancestor and two descendents

•  Encapsulation is an  ability to hide and protect data. AS3 has access level qualifiers such as public, private, protected and internal to control the access class variables and methods. In addition to a Java-like public, private, protected and package access levels, in AS3 you can also create namespaces that will give you yet another way of controlling access to properties and methods. However, if Java enforces object-oriented style of programming, this is not the case with AS3,  because it’s based on the scripting language standard. Object-oriented purists may not like the next code snippet, but this is how HelloWorld program may look in AS3:

trace("Hello, world");

That’s it. No class declaration is required for such a simple program, and the debug function trace() can live its own class-independent life, as opposed to Java’s println() doubly-wrapped in the classes System and PrintStream. You can write your own functions, attach them to dynamic objects and pass them as parameters to other functions. AS3 supports regular inheritance chain as well as so-called prototype inheritance when you can add new properties to the class definitions, and they will be available to all instances of this class. Moreover, you can disable validation of the properties and methods during compilation by turning off “strict” mode. In Java, behind every object instance there is an entity of type Class. This is not an object itself, but it’s placed in memory by class loaders.

Program Design with Interfaces and Polymorphism

As in Java, AS3 interfaces are special entities that define the behavior (methods) that can be implemented by classes using the keyword implement. After explaining crucial for OOP interfaces, we’ll discuss how to write generic code even without their.

To illustrate how you can design AS3 programs with interfaces, let's work on the following assignment:

A company has employees and consultants. Design classes to represent people working in this company. The classes may have  the following methods: changeAddress, giveDayOff, increasePay. Promotion can mean giving one day off and raising the salary by a specified percentage. For employees, the method increasePay should raise the yearly salary and, for consultants, it should increase their hourly rate.

First, we’ll add all common methods that are applicable to both employees and  consultants to the class Person.

package com.theriabook.oop {
    public class Person {
     var name:String;
      public function changeAddress(address: String): String {
         return "New address is"  + address;
      private function giveDayOff(): String {
         return "Class Person: Giving an extra a day off";

Listing 2. The Ancestor class:  Person

In the next step, we’ll add a new behavior that can be reused by multiple classes: an ability to increase the amount of a person’s paycheck. Let’s define an interface Payable:

package com.theriabook.oop
    public interface Payable
       function increasePay(percent:Number): String;        

Listing 3. Interface Payable

More than one class can implement this interface:

package com.theriabook.oop
    public class Employee extends Person implements Payable
       public function  increasePay(percent:Number):String {
         // Employee-specific code goes here …
        return "Class Employee:Increasing the salary by "+ percent + "%\n";
Listing 4. AS3 class Employee implementing Payable interface

package com.theriabook.oop
    public class Consultant extends Person  implements Payable {

      public function increasePay(percent:Number): String{
       // Consultant-specific code goes here …
       return   "Class Consultant: Increasing the hourly rate by " +  percent + "%\n";

Listing 5. Class Consultant implementing Payable

When the class Consultant declares that it implements  interface Payable, it “promises” to provide  implementation for all methods declared in this interface - in our case it’s just one method increasePay().  Why is it so important that the class will "keep the promise” and implement all interface’s methods? An interface is a description of some behavior(s). In our case the behavior Payable means existence of a method with the signature
boolean increasePay(int percent).

If any other class knows that Employee implements Payable, it can safely call any method declared in the Payable interface (see the interface example in class Promoter).
In Java, besides method declarations, interfaces can contain final static variables, but AS3 does not allow in interfaces anything but method declarations.

Interfaces is yet another workaround for the absence of multiple inheritance. A class can’t have two independent ancestors, but it can implement multiple interfaces, it just needs to implement all methods declared in all interfaces. One of the way to implement multiple ingeritance (we often use but do not recommend – use at your own risk) is to use “include” statement with complete implementation in all classes implementing interface:
    public class Consultant extends Person  implements Payable {
    include “payableImplementation.as”
public class Employee extends Person  implements Payable {
    include “payableImplementation.as”

For example, a class Consultant can be defined as follows:
class Consultant extends Person
     implements Payable, Sueable {…}
But if a program such as Promoter.mxml (see below) is interested only in Payable functions, it can cast the object only to  those interfaces it intends to use, for example:
var emp:Employee = new Employee();
var con:Consultant = new Consultant();
var person1:Payable = emp as Payable;
var person2:Payable = con as Payable;

Now we’ll write a MXML program Promoter,  which will use classes Employee and Consultant defined in the Listing 4 and 5.  On the button click it’ll create an array with a mix of employees and consultants, iterate through this array and cast it to Payable interface,  and then call the method increasePay() on each object in this collection.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Label y="10" text="Inheritance, Interfaces and Polymorphysm" width="398" height="35" fontWeight="bold" horizontalCenter="-16" fontSize="16"/>
    <mx:Button x="93" y="66" label="Increase Pay" width="172" fontSize="16" click="startPromoter()" id="starter"/>
    <mx:TextArea x="26" y="114" width="312" height="133" id="output" wordWrap="true" editable="false" borderStyle="inset"/>

            import com.theriabook.oop.*;
            function startPromoter():void{
              output.text="Starting global promotions...\n";

              var  workers:Array = new Array();
              workers.push(new Employee());
              workers.push(new Consultant());
              workers.push(new Employee());
              workers.push(new Employee());

              for(var i: int = 0; i < workers.length; i++) {
               // Raise the compensation of every worker using Payable
               //   interface
               var p: Payable = workers[i] as Payable;
               output.text+= p.increasePay(5);              
               //p.giveDayOff(); would not work. Payable does not know
               //                  about this function

              output.text+="Finished global promotions...";

Listing 6.  Promoter.mxml
The output of this program will look as follows:

The line p.increasePay(5);  in the listing above may look  a little confusing: how can we call a concrete method increasePay on a variable of an interface type?  Actually we call a method on a concrete instance of the Employee or a Consultant object, but by casting this instance to the type Payable we are just letting the  AVM know that we are only interested in methods which were declared in this particular interface.
•  Polymorphism – when you look at our Promoter from Listing 6, it looks like it calls the same method increasePay() on different types of objects, and it generates different output for each type. This is an example of polymorphic behavior.

In the real world, array workers would be populated from some external data source. For example, a program could get the person’s work status from the database and instantiate an appropriate concrete class. The loop in Promoter.mxml will remain the same even if we'll add some other types of workers inherited from the class Person! For example, to add a new category of a worker - a foreign contractor,  we’ll have to create a class ForeignContractor that implement the  method increasePays and  might be derived from the class Person. Our Promoter will keep casting all these objects  to the type  Payable during the run-time and call the  method increasePay of the current object from the array.  
Polymorphism allows you to avoid using switch or if statements with the type checking operator is.  Below is a bad (non-polymorphic) alternative to our loop from Promoter.mxml that checks the type of the object and calls type-specific methods increaseSalary() and increaseRate() (assuming that these methods were defined):
      for(var i: int = 0; i < workers.length; i++) {
         var p: Person = workers[i] as Person;
         if (p is Employee){
         } else if (p is Consultant) {

Listing 7.  A bad practice example
You’d need to modify the code above each time you add a new worker type.

Polymorphism without interfaces

If this would be a Java article, I could have patted myself on the back for providing a decent example of polymorphism. But I'd like to step into a little bit dangerous territory: let’s think of a more generic approach – do we even need to use interfaces to ensure that a particular object instance has a required function like increasePay? Of course not. Java has a powerful introspection and reflection mechanism, which allows to analyze which methods exist in the class in question. It’s important to remember though, that in Java object instances have only those methods that were defined in their classes (blueprints). This is not the case with AS3.

There is yet another urban myth that reflection is slow, and you should use it only if you have to. But this consideration is not valid for programs that run on the client’s PCs, because we do not have to worry about hundreds of threads competing for a slice of time of the same server’s CPU(s). Using reflection on the client is fine. Even on the server, a proper combining of reflection with caching allows avoiding any performance penalties.

AS3 provides very short and elegant syntax for introspection, and we’d like  to spend some time illustrating  polymorphism  without typecasting and strict Java-style  coding.

Let’s re-visit our sample application. Workers have  pay and benefits and vacations, consultants have hourly pay. But retirees may have some other forms of receiving pension, board of directors  might have pay with no benefits - are they workers? No they are not, and their objects  may not necessarily implement Payable interface, which means that the typecasting from Listing 6 would cause a run-time exception.

How about raising the compensation of every Person even if it does not implement Payable? If one of these objects will sneak into the array of workers, simple  casting to Payable show below will throw an exception

Payable p = Payable(workers[i]);

Let’s re-write the loop from Listing 6 as follows:

for(var i:uint = 0; i < workers.length; i++) {
 var p:* = workers[i]["increasePay"];
 output.text+=p==undefined?”no luck”:p(5);      

This short loop deserves explanations. First, we’ve declared a variable p of type *. This declaration means that p can be of any type.  Using an asterisk a bit more open than var p:Object; as it allows the variable p to have a special value of type undefined, which is used in the above code sample.  

Let’s dissect the following line:

var p:* = worker[i]["increasePay"];

It means, “Get a reference to the function increasePay() from the array element workers[i]. You may ask, why do you use the brackets around the increasePay instead of the dot notation? The reason being that dot notation would ask the compiler to find and validate this function, while the brackets tell compiler not to worry about it: the program will take care of this little something inside the brackets during the runtime.

Basically, this single line above performs the introspection and gets a pointer to the function increasePay for the future execution in the next line:
output.text+=p ==undefined?”no luck":p(5);

If this particular element of the workers array does not have increasePay defined (its class must be declared as dynamic), add “no luck” to the text field, otherwise execute this object’s  version of increasePay passing the number five as its argument. The line above still has a potential problem if the class does not have the function increasePay, but has a property with the same name. The bulletproof version looks like this:

  output.text+=!(p is Function)?"no luck":p(6);

Let’s emphasize again: this method increasePay does not have to be defined in any interface.

Java programmers would call this a wild anarchy. Of course, adhering to strict rules and contracts  in Java leads to more predictable code and less surprises during the run-time. But modern Java moves toward dynamic scripting, added implicit typecasting, run-time exceptions, etc. Overuse of interfaces, private, protected and other “nice and clean object-oriented techniques” does not promote creative thinking of software developers. By the way, protected variables is another weird thing in OOP.


Now raise your hand if you are a Java programmer and after reading this article, and you are  thinking to yourself, "Hmm, may be ActionScript 3 is not too bad and I should take a look at it ?". 
Now, stand up if you are thinking, "Java rules, the rest of programming languages sucks". 
ActionScript 2  programmers can remain seated, but might want to reconsider the way they program.

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.