Commit bf82cc6

mo <mo.khan@gmail.com>
2019-06-18 23:30:10
extract methods to make it easier to read
1 parent ae4c0a7
Changed files (1)
src/Q4/RandomSumGame.java
@@ -9,6 +9,7 @@ public class RandomSumGame {
   private int d2 = 0;
   private int sum = 0;
   private int valuePoint = 0;
+  private int wins = 0;
   private String status;
   private PrintStream out;
 
@@ -25,34 +26,9 @@ public class RandomSumGame {
     int total = d1 + d2;
     this.puts("You rolled: %d", total);
     if (!hasValuePoint()) {
-      switch (total) {
-        case 2:
-        case 3:
-        case 12:
-          this.puts("Craps! You lose.");
-          break;
-        case 7:
-        case 11:
-          this.puts("Natural! You win!");
-          break;
-        default:
-          this.puts("Value point established: %d", total);
-          this.valuePoint = total;
-          play();
-          break;
-      }
+      this.firstPlay(total);
     } else {
-      if (total == this.valuePoint) {
-        this.puts("You win!");
-        this.reset();
-        return;
-      } else if (total == 7) {
-        this.puts("You lose.");
-        this.reset();
-        return;
-      } else {
-        play();
-      }
+      this.subsequentPlay(total);
     }
   }
 
@@ -66,6 +42,42 @@ public class RandomSumGame {
     return new Random().nextInt(5) + 1;
   }
 
+  private void firstPlay(int total) {
+    switch (total) {
+      case 2:
+      case 3:
+      case 12:
+        this.lose("Craps! You lose.");
+        break;
+      case 7:
+      case 11:
+        this.win("Natural! You win!");
+        break;
+      default:
+        this.puts("Value point established: %d", total);
+        this.valuePoint = total;
+        play();
+        break;
+    }
+  }
+
+  private void subsequentPlay(int total) {
+    if (total == this.valuePoint) this.win("You win!");
+    else if (total == 7) this.lose("You lose.");
+    else play();
+  }
+
+  private void win(String message) {
+    this.wins += 1;
+    this.puts(message);
+    this.reset();
+  }
+
+  private void lose(String message) {
+    this.puts(message);
+    this.reset();
+  }
+
   private void puts(String format, Object... args) {
     this.out.println(String.format(format, args));
   }