CS II Lesson 15

Professor Abdul-Quader

Polymorphism III

Advising

  • Core next semester: Calc 1, CS1, Calc 3, Discrete
  • Electives next semester: Origins of Math, Data Science/Stats (new course: online format)
  • Also: ECO 3070 Econometrics, ECO 3080 Game Theory, NME 3240 Drawing, Moving, Seeing With Code, NME 3560 Physical Computing (may need advisor approval to count as ULE).
  • Next week: advising week. Make an appointment.

CoinGame

Today: simple coin flipping game for two players.

  • Not object-oriented!
  • Some changes may be hard…
    • …because it’s not object-oriented!

CoinGame

Simple coin flipping game for two players. It works as follows:

  1. First, a coin is flipped 9 times.
  2. A human player is then prompted to guess the number of heads.
  3. A computer player guesses the largest number left.
  4. A winner (or tie) is declared, based on whoever is closer to the real number.

Exercise

  1. Change the game so that the user can enter in the number of times we will flip the coin.
  2. Change the game so that the user can choose who guesses first (the human or the computer player).

(Surprisingly, one of these changes is much harder than the other.)

Hint

  • Why is this so hard to do?
  • The code is poorly designed.
  • Not modular, not object-oriented.
  • Move code out of main method into other classes / methods!
  • We will need polymorphism!

Single Responsibility Principle

Software development design principle that we should know of:

“There should never be more than one reason for a class to change.” (Robert Martin, aka “Uncle Bob”)

(Robert Martin is the author of Agile Software Development: Principles, Patterns, and Practices (2001))

Exercise

  1. Come up with a better strategy for the computer player. Change the game so that the user can select between the two strategies (Max / other strategy).
  2. Change the game to allow for multiple ways to play: Human vs Human, Computer vs Computer, etc. Allowing all possible strategies for computer players as well.

Paradigm

Code to interfaces, not implementations!

When you design classes/methods: don’t worry about the implementations of the parameters that are passed in. Just worry about what they can do.

Benefits of coding to interfaces

  1. Testability. We can quickly implement a “dummy” class which does nothing, and pass that in as an implementation to test out our method.
  2. Robustness. Our methods/classes do not rely upon implementation details, which may change in future versions of the code.
  3. Flexibility: we can easily / quickly swap out implementations depending on the situation. (Ex: today!)

Upcoming

  • Project 3 will be posted this week: due Wednesday, April 22.
    • Get started ASAP!
  • Thursday: Exam 2
  • Monday: asynchronous / small groups.
// reveal.js plugins