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
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, 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. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that CAST Software 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion 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. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
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.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of 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. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that TidalScale 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. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look 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 ...