Aiming for simplicity using a callable interface

The idea behind a callable object is that we have a class interface focused on a single method. This is also true for simple function definitions.

Some objects have multiple relevant methods. A Blackjack Hand, for example, has to add cards and produce a total. A Blackjack Player has to place bets, accept hands, and make play decisions (for example, hit, stand, split, insure, and double down). These are more complex interfaces that are not suitable to be callables.

The betting strategy, however, is a candidate for being a callable. While it will be implemented as several methods to set the state and get a bet, this seems excessive. For this simple case, the strategy can be a callable interface with a few public attributes.

The following is the straight betting strategy, which is always the same:

class BettingStrategy: 
    def __init__(self) -> None: 
       self.win = 0 
       self.loss = 0 
    def __call__(self) -> int: 
        return 1 
bet = BettingStrategy() 

The idea of this interface is that a Player object will inform the betting strategy of win amounts and loss amounts. The Player object might have methods such as the following to inform the betting strategy about the outcome:

    def win(self, amount) -> None: 
        self.bet.win += 1 
        self.stake += amount 
    def loss(self, amount) -> None: 
         self.bet.loss += 1 
         self.stake -= amount 

These methods inform a betting strategy object (the self.bet object) whether the hand was a win or a loss. When it's time to place a bet, the Player object will perform something like the following operation to get the current betting level:

    def initial_bet(self) -> int: 
        return self.bet() 

This is a pleasantly short method implementation. After all, the betting strategy doesn't do much other than encapsulate a few, relatively simple rules.

The compactness of the callable interface can be helpful. We don't have many method names, and we don't have a complex set of syntaxes for a class to represent something as simple as bet amount.

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

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