mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2026-01-12 13:15:18 -08:00
Clean up comments and convert Card to a record
This commit is contained in:
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user