How much sanity checking is required for function inputs?

Matt Wheeler m at funkyhat.org
Sat Apr 23 17:33:36 EDT 2016


On 22 April 2016 at 04:11, Christopher Reimer
<christopher_reimer at icloud.com> wrote:
> On 4/21/2016 7:10 PM, Ethan Furman wrote:
>>> 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.
>>
>> This will make it so you cannot use your PieceFactory for custom setups.
>
> The sanity check won't be in the PieceFactory, but in the Piece class as an
> interface and each Piece subclass will implement the correct positions for
> comparison.

This is still backwards to me. It prevents your classes from being
suitable for restoring a stored game state, not just custom starting
positions (which I think is what Ethan means by custom setups).

If you need to put sanity checking in your initialisation at all it
should be at some higher level, probably in a method named something
like `start_chess_game`. But really I'd suggest just writing tests for
that method to make sure it's doing the right thing.

On the other hand (and I'm sure you've already thought of this) it
probably does make sense to put piece move validation in to each of
the piece classes: you could even have some fun with it...

def move_straight(old, new):
    if old[0] == new[0] or old[1] == new[1]:
        return True

def move_diag(old, new):
    diff_x = abs(old[0] - new[0])
    diff_y = abs(old[1] - new[1])
    if diff_x == diff_y:
        return True

class Piece:
   ...
    def move(self, new):
        if self.validate_move(new):
            # do the move
            ...
        else: raise IllegalMove('or something')

class Queen(Piece):
    def validate_move(self, new):
        return any((test(self.position, new) for test in
(move_straight, move_diag)))


Ok I'll stop before I get too carried away... This is completely
untested so bugs will abound I'm sure :)

-- 
Matt Wheeler
http://funkyh.at



More information about the Python-list mailing list