From 51f173c9da27d362f34bc0e249e0a7c88a98b95a Mon Sep 17 00:00:00 2001 From: Dave Burke Date: Sun, 23 Jan 2022 21:18:32 -0600 Subject: [PATCH] Make Card immutable --- 10_Blackjack/java/src/Card.java | 46 +++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/10_Blackjack/java/src/Card.java b/10_Blackjack/java/src/Card.java index c4ccd50a..aa151742 100644 --- a/10_Blackjack/java/src/Card.java +++ b/10_Blackjack/java/src/Card.java @@ -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 { - HEARTS, DIAMONDS, SPADES, CLUBS; - } + public enum Suit { + HEARTS, DIAMONDS, SPADES, CLUBS; + } - private int value; - private Suit suit; + // 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 void setValue(int value) { - this.value = value; - } + public Card(int value, Suit suit) { + this.value = value; + this.suit = suit; + } - public int getValue() { - return this.value; - } - - public void setSuit(Suit suit) { - this.suit = suit; - } - - public Suit getSuit() { - return this.suit; + public int getValue() { + return this.value; } } \ No newline at end of file