Tuesday, August 5, 2008

Designing programs in Java


I've done my fair share of complaining about Java, and I still believe that the AP Computer Science exam should be in Python--a more flexible language with cleaner syntax and the ability to use Object-Oriented design if appropriate.

Truth is, though, that Java has a special appeal to my obsessive compulsive tendencies. There's something cozy about sitting down to write a relatively simple Java program. With Python I'm tempted to just start writing--and the development time in Python really is super fast. With Java, though, you need to plan things out ahead of time a little more. Of course that's a good idea in Python, too, but it's not enforced in the way Java enforces program planning.

Since I only have a week or so before school starts, I'm practicing my chops and staying sharp by writing a few programs here and there. Today I decided to write a Java version of the classic Hi-Lo Guessing Game. Rather than just starting to code, however, I thought about the program in detail beforehand, and made a few design choices that would help make the program something I may use in my programming classes (as an example of design). Let me elaborate.

The basic Hi-Lo simply has one playing guessing a number between two set values, like one and one hundred. The other player guesses a number, like 42. The first player than says "Higher" or "Lower" depending on the secret number. You know the game.

What I came up with, however, were three classes to use in a program:

1. ComputerPlayer
2. HiLoGameEngine
3. StatsKeeper

Now, each of those classes will have specific attributes and methods that they are responsible for. Using a procedural approach it would just be the one program and the human user, with the program responsible for all three roles that I've delegated to individual classes. Why do this? Because it's good design. Suppose I want to improve the AI of the ComputerPlayer class. Rather than tweak that class, I can extend it with a CleverComputerPlayer class, or even a CheatingComputerPlayer class. The StatsKeeper class may be reused in another program in the future--in a tic tac toe game, for instance. You can see the possibilities of Object Oriented Design in the long run; software can be reused for other applications.

Bringing this into the classroom will be fun. One of the weaknesses in the AP Computer Science curriculum, I think, is that it focuses on solitaire coding. In reality, especially in open source, but also on development teams, a programmer needs to know how to work on a team.

By the way, in my program the computer and human players switch roles and compete in a series of games, with the StatsKeeper recording all the results.

No comments: