Preface

Why Read This Book?

One way to master OO design is do design and implementation of a large number of classes. This book guides you through exercises to design dozens of classes that must work together to create a large – and reasonably complete – application. We’ll discuss the design in some detail to reveal an approach to object-oriented design.

While it is also important to read examples of good design, a finished product doesn’t reveal the designer’s decision-making process. Our goal in this book is to help programmer understand the design process that leads to a final product.

Everything is Design It’s important to note that all software development involves considerable skill in design. In some circles, there is an attempt to distinguish between architects (or designers) and coders. The idea is that someone can be able to work with a language – coding – but not quite ready to do design work. The coders can be given a detailed “specification” from which they can write code.

This distinction between designers and coders doesn’t really exist. It’s unhelpful to try and make this distinction. All programming involves design at some level.

If we attempt to write a design specification so detailed that someone else can transform it into code without them having to make any design decisions, the specification is isomorphic to code, but written in some non-technical language like English. The design has all the details of code. An automated translation could produce code from this magically complete with fewer errors than a person.

If we write specifications at somewhat more abstract level, we’re demanding that the “coder” makes some design decisions to move from the abstraction to concrete code. The more abstract the specification, the more design work must be done. The amount of design work is non-zero.

The point of this book is to build skills in object-oriented design prior to a project with a fixed budget and a looming deadline.

What You’ll Do

This book provides a sequence of interesting and moderately complex exercises in OO design. The exercises are not hypothetical, but must lead directly to working programs.

The applications we will build are a step above trivial, and will require some careful thought as part of creating a workable design. Further, because the applications are largely recreational in nature, they are interesting and engaging. This book allows the reader to explore the processes and artifacts of OO design before project deadlines make good design seem impossible.

The first part will be quite detailed. The third part will summarize the designs at a higher level of abstraction.

Audience

Our primary audience includes programmers who are new to OO programming.

Knowledge of the Python language is essential. Since the focus is on OO techniques, some exposure to class definitions is important. We will provide exercises that have four key features:

  • complex enough to require careful design work,
  • fun enough to be engaging,
  • easy enough that results are available immediately, and
  • can be built in simple stages.

We’ll provide a few additional details on language features. We’ll mark these as “Tips”. For more advanced students, these tips will be review material. We will not provide a thorough background in any programming language. The student is expected to know the basics of the language and tools.

Helpful additional skills include using one of the various unit test and documentation frameworks available. We’ve included information in the appendices.

Classroom Use. Instructors are always looking for classroom projects that are engaging, comprehensible, and focus on perfecting language skills. Many real-world applications require considerable explanation of the problem domain; the time spent reviewing background information detracts from the time available to do the relevant programming. While all application programming requires some domain knowledge, the idea behind these exercises is to pick a domain that many people know a little bit about. This allows an instructor to use some or all of these exercises without wasting precious classroom time on incidental details required to understand the problem.

Skills. This book assumes an introductory level of skill in the Python language. We’ll focus on Python 3.4 as a minimum, with references to features of Python 3.5

Student skills we expect include the following. If you can’t do these things, this book may be too advanced.

  • Create source files, compile and run application programs. While this may seem obvious, we don’t discuss any integrated development environment (IDE). We have to assume these basic skills are present.
  • Use of the core procedural programming constructs: variables, statements, exceptions, functions. We will not, for example, spend any time on design of loops that terminate properly.
  • Some exposure to class definitions and subclasses. This includes managing the basic features of inheritance, as well as overloaded method names.
  • Some exposure to the various kinds of built-in collections.
  • Optionally, some experience with a unit testing framework. See the appendices for supplemental exercises if you aren’t familiar with Python’s unittest or doctest.
  • Optionally, some experience writing formal documentation. For Python programmers, this means writing docstrings and using a tool like Epydoc or sphinx. See the appendices for supplemental exerises if you aren’t familiar with formal, deliverable documentation.

Organization of This Book

This book presents a series of exercises to build simulations of the common, popular casino table games: Roulette, Craps and Blackjack. Each simulation can be extended to include variations on the player’s betting system. With a simple statistical approach, we can show the realistic expectations for any betting system. Each of these games has a separate part in this book. Each part consists of a number of individual exercises to build the entire simulation. The completed project results in an application that can provide simple tabular results that shows the average losses expected from each betting strategy.

The interesting degree of freedom in each of the simulations is the player’s betting strategy. The design will permit easy adaptation and maintenance of the player’s strategies. The resulting application program can be extended by inserting additional betting systems, which allows exploration of what (if any) player actions can minimize the losses.

Roulette. For those who’ve never been in a casino, or seen movies that have casinos in them, Roulette is the game with the big wheel. They spin the wheel and toss in a marble. When the wheel stops spinning, the bin in which the marble rests defines the winning outcomes.

People who bet on the right things get money. People who bet on the wrong things lose money.

Starting in Roulette, we proceed slowly, building up the necessary application one class at a time. Since this is the simplest game, the individual classes reflect that simplicity. We focus on isolation of responsibilities, creating a considerable number of classes. The idea is to build skills in object design by applying those skills to a number of classes.

The first chapter of the part provides details on the game of Roulette and the problem that the simulation solves. The second chapter is an overview of the solution, setting out the highest-level design for the application software. This chapter includes a technique for doing a “walk-through” of the design to be confident that the design will actually solve the problem.

Each of the remaining sixteen chapters is a design and programming exercise to be completed by the student. Plus or minus a Frequently Asked Questions (FAQ) section, each chapter has the same basic structure: an overview of the components being designed, some design details, and a summary of the deliverables to be built. The overview section presents some justification and rationale for the design. This material should help the student understand why the particular design was chosen. The design section provides a more detailed specification of the class or classes to be built. This will include some technical information on Java or Python implementation techniques.

Craps. For those who’ve never been in a casino, or seen the play “Guys and Dolls”, Craps is the game with the dice. A player rolls (“shoots”) the dice. Sometimes there’s a great deal of shouting and clapping. A throw of the dice may – or may not – resolve bets. Additionally, a throw of the dice may also change the state of the game. A casino provides a number of visual cues as to the state of the game and the various bets.

In Craps, we build on the design patterns from Roulette. Craps, however, is a stateful game, so there is a more sophisticated design to handle the interactions between dice, game state and player. We exploit the State design pattern to show how the design pattern can be applied to this simple situation.

The first chapter is background information on the game of Craps, and the problem that the simulation solves. The second chapter is an overview of the solution, setting out the highest-level design for the application software. This chapter also provides a “walk-through” of the design.

Each of the remaining eleven chapters is an exercise to be completed by the student. Each chapter has the same basic structure: an overview of the component being designed, some design details, and a summary of the deliverables to be built.

Blackjack. For those who’ve never been in a casino, or seen a movie with Blackjack, Blackjack is a game with cards. The dealer deals two cards to themselves and each player. One of the dealer’s card is up and one is down, providing a little bit of information on the dealer’s hand. The players may ask for additional cards, or keep the hand they’ve got.

The idea is to build a hand that’s close to 21 points, but not more than 21. In Craps and Roulette there are a lot of bets, but few player decisions. In Blackjack, there are few bets, but really complex player decisions.

In Blackjack, the game states are more sophisticated than Craps or Roulette. In casino gift shops, you can buy small summary cards that enumerate all possible game states and responses. The more advanced student can tackle these sophisticated playing strategies. For the less advanced student we will simplify the strategies down to a few key conditions.

The first two chapters are background information on the game of Blackjack, the problem that the simulation solves, and an overview of the solution, setting out the highest-level design for the application software. Each of the remaining six chapters is an exercise to be completed by the student. Since this is more advanced material, and builds on previous work, this part has many simple deliverables compressed into the individual chapters.

Fit and Finish. We include several fit-and-finish issues in Fit and Finish. This includes more information and examples on unit testing and documentation.

Additionally, we cover some “main program” issues required to knit all of the software components together into a finished whole.

Why This Subject?

Casino table games may seem like an odd choice of subject matter for programming exercises. We find that casino games have a number of advantages for teaching OO design and OO programming.

  • Casino games have an almost ideal level of complexity. If they were too simple, the house edge would be too obvious and people would not play them. If they were too complex, people would not enjoy them as simple recreation. Years (centuries?) of experience in the gaming industry has fine-tuned the table games to fit nicely with the limits of our human intellect.
  • Simulation of discrete phenomena lies at the origin of OO programming. We have found it easier to motivate, explain and justify OO design when solving simulation problems. The student can then leverage this insight into other applications of OO programming for more common transactional applications.
  • The results are sophisticated but easy to interpret. Probability theory has been applied by others to develop precise expectations for each game. These simulations should produce results consistent with the known probabilities. This book will skim over the probability theory in order to focus on the programming. For a few exercises, the theoretical results will be provided to serve as checks on the correctness of the student’s work.
  • They’re more fun than most other programming problems.

This book does not endorse casino gaming. Indeed, one of the messages of this book is that all casino games are biased against the player. Even the most casual study of the results of the exercises will allow the student to see the magnitude of the house edge in each of the games presented.

Conventions Used in This Book

Here is how we might present code.

Typical Python Example

from collections import defaultdict
combo = defaultdict(int)
for i in range(1,7):
    for j in range(1,7):
        roll= i+j
        combo[roll] += 1
for n in range(2,13):
    print( "{0:d} {1:.2%}".format( n, combo[n]/36.0 ) )
  1. We create a Python dictionary, a map from key to value. We use the collections.defaultdict so that missing keys are created in the dictionary with an initial value created by the int() function.
  2. We iterate through all combinations of two dice, using variables i and j to represent each die.
  3. We sum the dice to create a roll. We increment the value in the dictionary based on the roll.
  4. Finally, we print each member of the resulting dictionary. We’ve used a sophisticated format string that interpolates a decimal value and a floating-point percentage value.

The output from the above program will be shown as follows:

2 2.78%
3 5.56%
4 8.33%
5 11.11%
6 13.89%
7 16.67%
8 13.89%
9 11.11%
10 8.33%
11 5.56%
12 2.78%

We will use the following type styles for references to a specific Class, method(), or variable.

Tip

Tips Look Like This

There will be design tips, and warnings, in the material for each exercise. These reflect considerations and lessons learned that aren’t typically clear to starting OO designers.