Private Methods
The Refactoring Approach: Extract a Helper Class
Sometimes the private method will be so complex that it's really an entity in its own right, and definitely warrants microtesting.
In this case:
- Extract the complex code into a new class, using public API's where the action is.
- Microtest that class.
- When you are ready, use a private member of the current class to point to the new class.
getHandTotal()
lives in the game class (Blackjack
),
You may recognize this as a case of the "Primitive Obsession" smell, where
important data, on which the code invokes interesting operations, is kept in a
List
as opposed to a domain class.
public class Blackjack {
private List<Card> playerHand;
private List<Card> dealerHand; public boolean didPlayerWin() {
return getHandTotal(playerHand) > getHandTotal(dealerHand);
} private int getHandTotal(List<Card> hand) {
int total = 0; for (Card card : hand) {
total += card.getValue();
} return total;
}
}
public class Blackjack {
private Player player;
private Player dealer; public bool didPlayerWin() {
return player.getHandTotal() > dealer.getHandTotal();
}
}
public class Player {
private List hand; public int getHandTotal() {
int total = 0; for (Card card : hand) {
total += card.getValue();
} return total;
}
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |