Tuesday, December 23, 2008

Object-Oriented Programming Example

My Java programming project is going a bit slow, but I have many excuses. The one I like to use in OOP (Object-Oriented Programming) is "well, I'm still working on some design issues before I start writing all the code."

So I'm converting Football Strategy, the old Avalon Hill game into a modern Java version, complete with opposing coach AI. OOP will allow me to extend the coach class through time, making better and better opponents for humans to face.

But that all comes later. Since I give my AP Computer Science students the whole year for their project, I too have a lot of time to develop this application. Recently I've been hitting my head against the wall trying to come up with a system for encoding play results that include all the relavent information in one result. For instance, a result of 723 may have used the 7 as a play-type indicator (say, "complete pass play that went out of bounds"), and the 23 might have been the net yardage. On the suggestion of one of my students, however, I have decided to encode all the play results as String objects. Perhaps something like "15cpno023" for complete pass no fumble out of bounds and 23 yards, with the play taking 15 seconds. I don't know, I'm not there yet.

The point of using an OOP approach, however, is to allow you to think of things as actual objects. What better way to do that then open up the Football Strategy game box and see what objects in the game may lend themselves to objects in Java. One that clearly lends itself to being a Java class is the scoreboard. Before OOP, making a football simulation would have been a long and tedious process, as the data would just be flying around the program, jumping from function to function. With OOP, though, you get to break things up and decide where the data lives. In the case of a footballScoreboard class, you can easily think of the data fields (homeScore, awayScore, down, yardsToGo, fieldPosition, etc) and the various behaviors (incrementDown, incrementHomeScore, etc). What was so nice about this, though, was that there is an actual object in the real world that is so familiar to anyone who has ever been a football fan. Ask some football fans at random to draw a football scoreboard and a lot of them would draw something like this post's image.

Coming from a procedural programming background, OOP was a bit strange at first. Now I can't imagine programming relatively large projects without it.

No comments: