How much sanity checking is required for function inputs?

Tim Chase python.list at tim.thechases.com
Thu Apr 21 21:54:59 EDT 2016


On 2016-04-21 18:34, Christopher Reimer wrote:
> 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)

I'd simplify this code to something like

  class PieceFactory(object):
    @staticmethod
    def factory(color, piece, position):
      try:
        return {
          'Bishop': Bishop,
          'King': King,
          'Knight': Knight,
          'Pawn': Pawn,
          'Queen': Queen,
          'Rook': Rook,
          }[piece](color, position)
      except KeyError:
        raise PieceException(...)

which removes some of the redundancy.  I might even be tempted to
simply ignore the exception and let the KeyError percolate up the
call-stack if someone calls it with an unknown piece/key, rather
than converting it into a PieceException.

-tkc







More information about the Python-list mailing list