Clean up comments and convert Card to a record

This commit is contained in:
Mitch Peck
2022-03-18 12:52:14 -05:00
parent 88202ec9be
commit 0b1f809707
3 changed files with 21 additions and 43 deletions

View File

@@ -1,37 +1,27 @@
/**
* This is an example of an "immutable" class in Java. That's just a fancy way
* This is an example of an "record" class in Java. That's just a fancy way
* of saying the properties (value and suit) can't change after the object has
* been created (it has no 'setter' methods and the properties are 'final').
* been created (it has no 'setter' methods and the properties are implicitly 'final').
*
* Immutability often makes it easier to reason about code logic and avoid
* certain classes of bugs.
*
* Since it would never make sense for a card to change in the middle of a game,
* this is a good candidate for immutability.
*
*/
// TODO consider making this a Record
public final class Card {
record Card(int value, Suit suit) {
public enum Suit {
HEARTS, DIAMONDS, SPADES, CLUBS;
}
// Since this class is immutable, there's no reason these couldn't be
// 'public', but the pattern of using 'getters' is more consistent with
// typical Java coding patterns.
private final int value;
private final Suit suit;
public Card(int value, Suit suit) {
public Card {
if(value < 1 || value > 13) {
throw new IllegalArgumentException("Invalid card value " + value);
}
if(suit == null) {
throw new IllegalArgumentException("Card suit must be non-null");
}
this.value = value;
this.suit = suit;
}
public int getValue() {