Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: Article

An OO Approach to War

An OO Approach to War

With the advent of ColdFusion components (CFCs), introduced in ColdFusion MX version 6.0 and greatly improved in version 6.1, ColdFusion MX allows CF programmers to enter the mainstream of object-oriented (OO) programming. With the overwhelming success of the J2EE and the .NET platforms, OO has become the dominant paradigm for building commercial software and gaining a thorough, working knowledge of it is essential to any programmer's long-term career success. In this article, we'll build a simple version of the child's card game, "War" ­ hopefully learning something about OO design and implementation along the way.

Here's a refresher on the game: two players each receive a card. The cards are then compared to see which has a greater value (the ordering of suits is ignored for this game). The player with the higher card is the winner and the game continues until the deck of cards runs out. As simple as the game is, it does provide some insight into object orientation as implemented in CFCs. First, though, we need to understand what OO is and how it requires a shift in thinking.

As most ColdFusion programmers write code, data and program logic are separate. Data is stored in databases while program logic is fit into CFML files. When we need to read or modify a piece of data, we commonly extract it from its database home, use it, and then return it (see Image I).

OO takes a different approach: both data and logic are combined into a single software "packet" known as a class. Data is stored in instance variables and logic is stored in methods.

In the address example I've used, we would build an Address class. What sort of data would an Address class have? A minimal representation of an Address class would probably include street, city, state, and zip. Because the Address class isn't expected to do much, its methods might be restricted to "getters" and "setters" for the instance variables, yielding methods like getStreet and setStreet. These methods (and similar ones for the other instance variables) simply provide access to the data that is kept private.

In ColdFusion MX, classes have a special name: ColdFusion components (or CFCs, for short). Code I shows one CFC implementation for an Address type.

A class is a static representation of something in the real world. But we don't want a static address; we want an actual address. Our class definition acts as a sort of blueprint or cookie cutter, from which individual objects can be created - and it's objects we're counting on to do the work in an object oriented application.

Creating an object from a class is quite simple:

<cfset myAddress = CreateObject('component', 'Address') />

That's it. We now have an object referred to by the name, myAddress. Our object is pretty barren at present. All it has for instance variables are empty strings. We'll give the instance variables more meaningful data, but first, we need to understand a very important OO idea - perhaps the most important idea.

Encapsulation is a principle that urges us to keep our data private to the outside world, allowing access to it only through methods. With CFCs, we achieve this by placing the instance variables in a private scope (private to the object itself) known as the variables scope. From outside the object, those variables don't seem to exist. We can try to access them - perhaps using dot notation:


But ColdFusion will tell us that no such variables could be found. That's right - since they're private, the only way to access these is through the getter and setter methods we created. Here's how we can get real data into our object:

<cfset myAddress.setStreet('4034 Whetstone Ct') />
<cfset myAddress.setCity('Marietta') />
<cfset myAddress.setState('GA') />
<cfset myAddress.setZip('30062') />

Our setters work to set values for instance variables; our getters provide the information stored in those variables.

People often ask me if it's hot in #myAddress.getState()#.

Once we have an object, we can get it to do some useful work. We do so by sending the object a message. We saw a simple example of this with our getters and setters. The methods defined by an object define the messages that can be sent to that object and regardless of how complex the object may be, we always use this message-sending to accomplish things.

In addition to encapsulation, OO is upheld by two other chief tenets: polymorphism and inheritance. With CFCs especially, these two are intimately related. The word polymorphism is an unhappy transplant from its native Greek, where it meant "many forms." As applied to OO, it might be better translated "much confusion." Polymorphism is notoriously hard to define - and that's too bad, because it's a powerful tool in the hands of accomplished programmers. Still, let's see if we can't discover what polymorphism is.

I'll start by asking a simple question: Who are you? Well, that depends. You may be a child to some, a parent to others, an employee to your company, a spouse to your mate, a friend to your comrades - the list is probably a very long one. What's important for our understanding of polymorphism is that you belong to many different groups. Here, we've listed Child, Parent, Employee, Spouse, and Friend.

OO languages allow us to create a software model of the world, or at least those parts of it that are under consideration. Part of the language's job is to make sure that conversations between objects (via message sending) is safe - that is, the object that is being sent a message has a method that correlates with the message sent. The way that class-based OO languages (Java, C#, CFCs) provide for this is through type checking. The logic behind this is as old as Aristotle, who laid out the basic law of the syllogism like this:

  1. Socrates is a man.
  2. All men are mortal.
  3. Socrates is mortal.
If the first two premises are granted, the conclusion is inescapable. Likewise, OO languages implement their own version of syllogistic logic:
  1. You are a parent.
  2. All parents worry.
  3. You worry.
Put in slightly more techie terms, I could say that since you're of type Parent, you can respond to the worry() message. But parents are not all the same. Some are NaturalParents. Others are AdoptiveParents. Still others are SpiritualParents. No matter; they all know all too well how to respond to the worry() message. Again, translating this into TechTalk, we might draw a UML class diagram that looks something like this Image II.

Now we get to the polymorphic part: let's say that we have a Counselor type, who specializes in helping parents deal with worry. The Counselor has a soothe() method.

<cffunction name="soothe" access="public" returntype="void" output="false">
	<cfargument name="parent" type="???" required="true" />
	<!--- secret parent-soothing method goes here --->

We specified an argument named parent, but of what type? We certainly don't want to have methods for each type - sootheNaturalParent(), sootheAdoptiveParent(), and sootheSpiritualParent(). That's just a bad solution. Not only is it ugly, it's fragile. If we add a new kind of parent in response to changing requirements, we're going to have to find every method that accepts parent types and add new methods to correspond with the new parent type.

Luckily, polymorphism comes to the rescue: we can specify that the argument type is simply Parent. At run time, we can pass a Parent type, or - this is the important part - we can also pass any Parent subtype. The generalized Parent type provides a type specification for which any subtypes will be considered valid. So we don't need different methods for each type of parent. We can specify that the type is Parent and our code will run correctly. If we add another Parent subtype later, none of the code that accepts type, Parent, will break. This new Parent subtype can safely be passed to the existing methods.

There's another aspect to polymorphism. Image III is another UML diagram showing a polymorphic relationship.

Now, in a Boss class, we might have a method called delegateWork() that accepts an Employee and calls the Employee's work() method. The code might look like this:

<cffunction name="delegateWork" access="public" returntype="void"
	<cfargument name="employee" type="Employee" required="true" />
	<cfset arguments.employee.work() />

As each Employee is sent to the Boss's delegateWork() method, the Boss tells the Employee to start working.

What happens? The PayrollClerk starts paying people; the Engineer starts designing things; and the Programmer starts writing code. Even though a generic Employee is accepted as the type of delegateWork method, the actual work method called on that Employee will be that one the corresponds with their more specific type. This prevents the Boss from needing a series of methods such as delegateWorkToPayrollClerk(), delegateWorkToEngineer - and so on.

Polymorphism (also known as subtype polymorphism) is a powerful tool to be used in building scalable and maintainable code. To make use of polymorphism in our OO code, we need to think in terms of general types, for which individual subtypes can later be substituted. This provides flexibility to our designs.

With CFCs, subtype polymorphism occurs by means of inheritance - whereby one class is a specialized type of another, existing class. A SportsCar is a specialized type of a Car, for example. To reflect this relationship in code, the subclass (SportsCar, in this example) declares that it extends a base class:

<cfcomponent displayname="SportsCar" extends="Car"…>

A class that extends another class has access to the base class's properties and methods, as though they were its own. Since Car will already have a start() and stop() method, for example, SportsCar doesn't need to define these itself - SportsCar inherits them from Car. (If a subclass wishes to implement a method differently from its base class, it may simply redefine the method in its own code. At run time, the overridden method, as it's called, will be invoked instead of the base class's method.)

Back to the Game
With that quick primer on object orientation done, let's return to our War card game. The game uses a standard set of poker cards. I began by modeling a single card in a CFC called Card. A Card needs to do only a few things. It must be able to return a string representation of its value ("Jack", for example), a numeric representation of its value (11 in the case of Jack) and it must be able to determine if it outranks another card. The public methods for Card are therefore getStringValue(): string , getNumericValue(): numeric, and compareTo(Card): numeric. (The syntax for expressing method signatures as they're called is this: any arguments accepted by the method are shown in parentheses; if the method returns anything, the return type is specified after the colon. Parsing the "compareTo(Card):numeric" method signature would tell us that the compareTo() method accepts a variable of type Card, and returns a value of type numeric.)

At about this point in the process, I remembered that different games use different card types, differing chiefly in the numeric value assigned to cards. To build in for this flexibility, should the need later arise, I created a specific PokerCard class that extends the Card CFC. To reflect the fact that different card types might have different numeric representations for the same card (an Ace might be counted as 1 or 11, for example), I decided that all specific Card subtypes should determine the numeric values for each card.

I decided to call this needed method initializeValueMap(). Since it would be specific to each subclass of Card, I wanted a way to ensure that all subclasses would implement the initializeValueMap() method. In languages such as Java and C#, I could mark the method in Card as abstract. The compiler would force all subclasses to implement the method.

In CFCs we have to find a different mechanism, as no concept of abstract yet exists. I chose to have the base Card CFC throw an error as its implementation of initializeValueMap(). If each subclass overrides the method, the error will never be thrown. If a subclass fails to override, however, the base class's method will be called and the error raised.

The compareTo(Card) method receives an object of type Card (note that the type is deliberately made general). The Card object uses the value map set by the subclass to determine its ranking compared to the argument sent to it. It returns a number: 1 if it outranks the passed-in Card, -1 if it is outranked, and 0 if both Cards have the same value.

A single playing card is part of a card deck, of course, and our next class must model the deck. I used the same type-subtype scheme to create a CardDeck and a PokerDeck class. The methods of the base class, CardDeck, include dealCard(): Card, hasNext(): boolean, shuffle(), getDealtCards(): array, and getUndealtCards(): array.

In addition to these public methods, CardDeck defines the private method, newDeck(), which generates individual Cards and clears the undealtCards array. The shuffle() method uses the newDeck() method and both are meant to be overridden in subclasses. To help ensure this, the methods throw errors in the base class.

One of the advantages of OO is greater reusability of code, and we note that these four classes can be used to create many different card games. Our War card game will be implemented as a CFC, War, that uses both PokerCard and PokerDeck and their superclasses (superclass is another term for base class).

The class has the following public methods: play(): string, setDeck(CardDeck). In addition, all of the classes we've seen have an init() method, which deserves some explanation. Most OO languages have the concept of a special "method," called a constructor that is automatically called when a new object is created. This is used to initialize variables and prepare the object for use.

Unfortunately, at this point, CFCs have no built-in constructor, so ColdFusion developers (intrepid lot that they are) have coalesced around a pseudo-constructor called init(). While it's not called automatically, developers adopt the habit of always instantiating a CFC using the following syntax:

<cfset objectName = CreateObject('component', 'CFCname').init() />

The init() method can accept arguments and always returns the newly created object, once any initialization occurs. I recommend that all your CFCs have an init() method - even those CFCs that need no initialization. This allows developers to always create new objects using the syntax shown above.

Note that the init() method of our War.cfc accepts a CardDeck. If you wanted to create your own version of War that worked slightly differently, you might do so by passing a CardDeck of Card types that implement compareTo(Card): boolean a bit differently. You could, for example, create a War game in which the lowest card always wins.

The play method deals cards to two players, identified as Red and Blue. It calls one of the card's compareTo() method, sending it the other card. Finally, it returns a string indicating who won and what the current score is.

To test out the system, I created a very simple Tester.cfm file:

<cfset pd = CreateObject('component', 'PokerDeck').init() />
<cfset game = CreateObject('component', 'War').init(pd) />
	<cfloop condition="#game.getDeck().hasNext()#">

While there are remaining undealt cards, the game will play the cards and will report whether Red or Blue finally won.

If you're new to CFCs and/or OO, you might want to take this code and expand it. You might add code to account for the situation when a tie occurs. In the real game, a "war" is declared and three cards are dealt. The winner of the next deal wins that hand plus all six of the "war" cards. Or, you might decide to build an interface to the system that will allow it to be played by real people. You can download the code at halhelms.com/index.cfm?fuseaction=code.detail.

From this simple example, we can see encapsulation, polymorphism, and inheritance at work. These three tenets of OO, when properly used, can help us write code that is robust, reusable, and maintainable.

More Stories By Hal Helms

Hal Helms is a well-known speaker/writer/strategist on software development issues. He holds training sessions on Java, ColdFusion, and software development processes. He authors a popular monthly newsletter series. For more information, contact him at hal (at) halhelms.com or see his website, www.halhelms.com.

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
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists looked at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deliver...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...