Becoming friend-ly

A relatively small number of languages have the equivalent of the C++ friend keyword. For example, Microsoft C# has the InternalsVisibleToAttribute class that can be used to grant access from specified contexts.

While many consider the friend keyword to be “dirty programming” and to violate principles of encapsulation,4 it is often cited as having positive value for testing purposes, especially unit testing. Consider a C++ implementation of a poker hand (Listing 9-10), in this case in a simple game of five-card stud. Of course, you do not want to reveal your cards to anyone else.

4. You can find a good discussion of this at www.cprogramming.com/tutorial/friends.html. Scott Meyers infers something similar when he says, “It also eliminates the need for a friend declaration, which many regard as tacky in its own right” [MEC, p. 131].

Listing 9-10: A C++ class with some justifiably private members

class MyPokerHand
{
private:
  Card hand[5];
public:
  void receiveCard(Card& card);
  void layDownCard(Card& card);
  void evaluateHand();
};

While other players and the dealer should not see your cards until you lay them down, your test should be able to see the cards so that it can verify that you evaluate your hand correctly for play. By adding

friend class MyPokerHandTest;

to the MyPokerHand class, our tests can inspect the cards to make sure the playing strategy will win the wealth and riches we expect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.221.133