I'm currently writing a game of chess, and, more specifically, I'm creating the code for the game board. The board is simply a static class that contains a multi-dimensional array representing the board, and methods to interact with it. The method in question for the purposes of this question, is called TryGetEntity
:
private static GameEntity[,] _board = new GameEntity[8,8];
...
public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity) {
occupyingEntity = null;
if (_board.GetLength(0) < requestedPosition.X || _board.GetLength(1) < requestedPosition.Y)
return false;
if (_board[requestedPosition.X, requestedPosition.Y] != null)
occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];
else return false;
return true;
}
My concern with this implementation is the default return value of true
. I've been taught over many years to assume failure which loosely translates to returning false
by default. Currently, I'm at war with myself on refactoring this to:
occupyingEntity = null;
if (_board.GetLength(0) >= requestedPosition.X || _board.GetLength(1) >= requestedPosition.Y) {
if (_board[requestedPosition.X, requestedPosition.Y] != null) {
occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];
return true;
}
}
return false;
I personally think that the second version reads better, but I'm wanting a second (or more) opinion on it.
Edit: Per request from the comments, here is the entire GameBoard
class, along with an example use-case (this project is still in very early phases, so no actual calls exist yet):
public static class GameBoard {
private static GameEntity[,] _board = new GameEntity[8,8];
public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity) {
occupyingEntity = null;
if (_board.GetLength(0) >= requestedPosition.X || _board.GetLength(1) >= requestedPosition.Y) {
if (_board[requestedPosition.X, requestedPosition.Y] != null) {
occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];
return true;
}
}
return false;
}
}
// Example use-case:
var requestedCoordinate = new BoardCoordinate(3, 3);
if (GameBoard.TryGetEntity(requestedCoordinate, out GameEntity occupyingPiece))
CapturePiece(occupyingPiece);
else
MoveToPosition(requestedCoordinate);
Does this implementation of the try pattern, in its originally presented state, seem easy to follow? How about the second version?
Edit: I think, that by posting this question, I sort-of answered it. Given that it made me stop and seek a second opinion in its original state, I suspect the same would be true for others. Additionally, now that I've gotten some sleep, the first version is much harder to read than the second. It's not more complex, just, cluttered and doing too much. I'll keep this question up for others to answer in greater detail, but I'm not going to be surprised if the consensus is "the first method is harder to read".
Note: Let's ignore formatting for this post.