Java Reference
In-Depth Information
to represent the different kinds of chess pieces, you might use a simple
enum like this:
[2]
This example is based on an example given by Tim Peierls.
enum ChessPiece {
PAWN, ROOK, BISHOP, KNIGHT, KING, QUEEN;
}
The rules for manipulating the different chess pieces could be defined in
a class
ChessRules
, which might then have a method that returns the set
of reachable positions for a given kind of piece, given its current posi-
tion:
Set<Position> reachable(ChessPiece type, Position current) {
if (type == ChessPiece.PAWN)
return pawnReachable(current);
else if (type == ChessPiece.ROOK)
return rookReachable(current);
// ...
else if (type == ChessPiece.QUEEN)
return queenReachable(current);
else
throw new Error("Unknown type");
}
The job of
reachable
is to dispatch actual calculations to methods that
know how to handle specific chess pieces, so it has to consider all the
possible values of the chess piece type that was passed to it. Whenever
you see a chain of
ifelse
statements, as above, or equivalently a
switch
statement (which you'll learn about in
Chapter 10
) that distinguishes
different objects or types of object, ask yourself if there is a way to have
the object decide what needs to be doneafter all, each object knows
what it is. In this case, why can't you ask the chess piece for its set of