c++oopinheritanceobject-compositionobject-design

Redundant code in composition class C++


I'm trying to pick up C++. Everything was going well until my 'practice' program hit I very minor snag. That snag, I believe, stems from a design issue.

Think of Blackjack(21). I made a few classes.

  1. Card
  2. Deck
  3. Hand
  4. Player

A Deck consists of - for simplicities sake - Has An array of cards.
-It can show all it cards
-It can shuffle
-It can remove cards

A Hand Is A Deck -with the benefit of
-It can calculate its hand value
-It can add Cards to the hand

Now to get to my issue - the Player design

-A Player Has A hand (private access)
My problem with player, is that hand has a method function called addCardToHand. I feel a sense of redundancy/bad design if I have to create a Player method called addCardToHand(Card c) in which calls and passes to the same method in hand.

or

declare Hand h as a public accessible member and in 'main()' do something like
Player p;
Card aCard;
p.h.addCard(aCard);

Any advice would be enlightening and highly appreciated. Keep in mind I am learning.


Solution

  • The best answer here is: it depends :) I'll try to clarify it a little, though.

    The first question is: does the Player class have any inner logic? If it's a simple container for Hand, I'd simply write Player.GetHand().AddCard(), because there is no reason to duplicate the code inside Player.AddCard() method, and the problem is solved.

    Let's suppose now, that there is a need for implementing additional logic for adding a card to Player's hand. That means, that additional code in Player class has to be called while adding a card to Hand. In such case, I see three possible solutions.

    (Sources only for demonstration purposes, may not compile)

    Personally, In the second case, I would choose the second solution - it's quite straightforward and easy to extend and reuse in case of further needs.