Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #107469

Re: How much sanity checking is required for function inputs?

From Christopher Reimer <christopher_reimer@icloud.com>
Newsgroups comp.lang.python
Subject Re: How much sanity checking is required for function inputs?
Date 2016-04-21 18:34 -0700
Message-ID <mailman.0.1461288908.2861.python-list@python.org> (permalink)
References (1 earlier) <1461131475.4042173.584042297.03DAB00E@webmail.messagingengine.com> <57171D23.40709@stoneleaf.us> <1461133057.4046578.584060569.2DD34821@webmail.messagingengine.com> <57185E88.30201@yahoo.com> <57197FC3.4030701@icloud.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: How much sanity checking is required for function inputs? Christopher Reimer <christopher_reimer@icloud.com> - 2016-04-21 18:34 -0700
  Re: How much sanity checking is required for function inputs? Steven D'Aprano <steve@pearwood.info> - 2016-04-22 12:22 +1000

csiph-web