How much sanity checking is required for function inputs?

Christopher Reimer christopher_reimer at icloud.com
Thu Apr 21 21:34:59 EDT 2016


Greetings,

Thanks to everyone for providing feedback. Here's my revised code to 
generate a set of chess pieces.


class PieceFactory(object):

         def factory(color, piece, position):
             if piece == 'Bishop':
                 return Bishop(color, position)
             if piece == 'King':
                 return King(color, position)
             if piece == 'Knight':
                 return Knight(color, position)
             if piece == 'Pawn':
                 return Pawn(color, position)
             if piece == 'Queen':
                 return Queen(color, position)
             if piece == 'Rook':
                 return Rook(color, position)

             raise PieceException('No valid Piece object for factory, 
got {}'
                                  ' instead'.format(piece))

         factory = staticmethod(factory)


def generate_set(color, pieces, positions):

     for piece, position in zip(pieces, positions):
         yield getattr(PieceFactory, 'factory')(color, piece, position)


The input values for 'pieces' and 'positions' are 16-item lists zipped 
together to produce a piece name and a position coordinate for the 
factory method. With slight modifications to the code, the factory 
method could also return checker pieces.

I got the factory method from here: 
http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Factory.html

I do plan to incorporate a sanity test in each Piece class to validate 
the initial position value. Pawns have 16 specific positions. Bishop, 
Knight and Rook each have four specific positions. King and Queen each 
have two specific positions. An invalid value will raise an exception.

Finally, VARS['VARIABLE_NAME'] got change to const['variable_name']. 
Should smell better.

Thanks,

Chris R




More information about the Python-list mailing list