Make Card immutable

This commit is contained in:
Dave Burke
2022-01-23 21:18:32 -06:00
parent 7bf2a0443b
commit 51f173c9da

View File

@@ -1,26 +1,34 @@
public class Card { /**
* This is an example of an "immutable" 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').
*
* 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.
*
*/
public final class Card {
public enum Suit { public enum Suit {
HEARTS, DIAMONDS, SPADES, CLUBS; HEARTS, DIAMONDS, SPADES, CLUBS;
} }
private int value; // Since this class is immutable, there's no reason these couldn't be
private Suit suit; // 'public', but the pattern of using 'getters' is more consistent with
// typical Java coding patterns.
private final int value;
private final Suit suit;
public void setValue(int value) { public Card(int value, Suit suit) {
this.value = value; this.value = value;
} this.suit = suit;
}
public int getValue() { public int getValue() {
return this.value; return this.value;
}
public void setSuit(Suit suit) {
this.suit = suit;
}
public Suit getSuit() {
return this.suit;
} }
} }