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 playerHand;
private List dealerHand;
... public boolean DidPlayerWin()
{
return GetHandTotal(playerHand) > GetHandTotal(dealerHand);
} // a public API private int GetHandTotal(IList hand)
{
int total = 0;
foreach (Card card in hand)
total += card.value;
return total;
} // some complex logic we want to test.
}
public class Blackjack
{
private Player player;
private Player dealer; public boolean DidPlayerWin()
{
return player.GetHandTotal() > dealer.GetHandTotal();
} // a public API
…
}
public class Player
{
private IList hand; public int GetHandTotal()
{
int total = 0;
foreach (Card card in hand)
total += card.value;
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(...)`` |