The Most Comprehensive "New-Media" Breaking News and Blog Site

Poker News on Ulitzer

Subscribe to Poker News on Ulitzer: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get Poker News on Ulitzer: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Poker Authors: Mark O'Neill, David H Deans, Ted McLaughlan

Related Topics: ColdFusion on Ulitzer, Java EE Journal, Poker News on Ulitzer

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