Skip to content

Commit d2f3c99

Browse files
committed
Day 2 - simplify switch statements
1 parent 64274d9 commit d2f3c99

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

src/test/java/com/macasaet/Day02.java

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -83,18 +83,19 @@ public Shape beats() {
8383
};
8484

8585
public static Shape forChar(final int c) {
86-
switch (c) {
86+
return switch (c) {
8787
case 'X':
8888
case 'A':
89-
return Shape.Rock;
89+
yield Shape.Rock;
9090
case 'Y':
9191
case 'B':
92-
return Shape.Paper;
92+
yield Shape.Paper;
9393
case 'Z':
9494
case 'C':
95-
return Shape.Scissors;
96-
}
97-
throw new IllegalArgumentException();
95+
yield Shape.Scissors;
96+
default:
97+
throw new IllegalArgumentException("Invalid shape: " + c);
98+
};
9899
}
99100

100101
/**
@@ -134,15 +135,12 @@ public Shape respond(Shape opponent) {
134135
};
135136

136137
public static ResponseStrategy forChar(final char c) {
137-
switch (c) {
138-
case 'X':
139-
return Lose;
140-
case 'Y':
141-
return Draw;
142-
case 'Z':
143-
return Win;
144-
}
145-
throw new IllegalArgumentException();
138+
return switch (c) {
139+
case 'X' -> Lose;
140+
case 'Y' -> Draw;
141+
case 'Z' -> Win;
142+
default -> throw new IllegalArgumentException("Invalid strategy: " + c);
143+
};
146144
}
147145

148146
public abstract Shape respond(final Shape opponent);

0 commit comments

Comments
 (0)