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.
class Blackjack…
private:
list<Card> playerHand;
list<Card> dealerHand;public:
bool didPlayerWin()
{
return getHandTotal(playerHand) > getHandTotal(dealerHand);
} // a public APIprivate:
int getHandTotal(list<Card>& hand)
{
int total = 0;
for (list<Card>::iterator iCard = hand.begin(); iCard != hand.end(); ++iCard)
{
total += iCard->value;
}
return total;
} // some complex logic we want to test.
class Blackjack…
private:
Player m_player;
Player m_dealer;public:
bool didPlayerWin()
{
return m_player.getHandTotal() > m_dealer.getHandTotal();
} // a public APIclass Player…
private:
list<Card> m_hand;public:
int getHandTotal()
{
int total = 0;
for (list<Card>::iterator iCard = m_hand.begin(); iCard != m_hand.end(); ++iCard)
total += iCard->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(...)`` |