Welcome!

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
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:


<cfoutput>
	#myAddress.street#
</cfoutput>

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 --->
</cffunction>

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"
output="false">
	<cfargument name="employee" type="Employee" required="true" />
	<cfset arguments.employee.work() />
</cffunction>

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) />
<cfoutput>
	<cfloop condition="#game.getDeck().hasNext()#">
	#game.play()#
	</cfloop>
</cfoutput>

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

Conclusion
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
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.
"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.
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...
"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.
"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...
"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.
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 ...
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.
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...
"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...
"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.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
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 ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...