How much sanity checking is required for function inputs?

Steven D'Aprano steve at pearwood.info
Thu Apr 21 22:22:09 EDT 2016


On Fri, 22 Apr 2016 11:34 am, Christopher Reimer wrote:

> 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)


Eww :-)

Creating an entire class with no state just to hold one method is an abuse
of classes. If your class doesn't include both state (data) and behaviour
(methods), it probably shouldn't be a class.


class King: ...
class Queeen: ... 
# etc.

PIECES = dict((piece.__name__, piece) for piece in 
              [King, Queen, Bishop, Knight, Rook, Pawn])

def make_piece(color, name, position):
    name = name.title()  # Accept 'king', 'KING', 'King' etc.
    P = PIECES.get(name, None)
    if P is None:
        raise PieceException('unknown name %r' % name)
    return P(color, position)



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


def generate_pieces(color, names, positions):
    for name, position in zip(names, positions):
        yield make_piece(color, name, position)




-- 
Steven




More information about the Python-list mailing list