I'm trying to make an abstract board game. In the game, a player can choose to make multiple actions within one turn such as placing, moving, or rotating a piece. I'm not sure if whether or not my implementation is bad. I was told by my professor that using instanceof and if statements like this is a sign of code smell, but I can't really think of any other way of implementing this.
My current motivation for implementing the game like this is to be able to dynamically order the different actions into a list so that the board can execute the actions. However, each action is different and has to be executed differently. So since I have to be able to list each action in any order and execute each action, this was the best way that I could think of.
public class Board {
private Square[][] squares;
public void execute(List<Action> actions) {
for (Action action : actions) {
if (action instanceof MovingAction) {
//
} else if (action instanceof RotatingAction) {
//
}
}
}
}
public interface Action {
}
public class MovingAction implements Action {
private Position positionOfPiece;
private Position targetPosition;
public Position getPositionOfPiece() {
return positionOfPiece;
}
public Position getTargetPosition() {
return targetPosition;
}
public MovingAction(Position positionOfPiece, Position targetPosition) {
this.positionOfPiece = positionOfPiece;
this.targetPosition = targetPosition;
}
}
public class RotationAction implements Action {
private Position positionOfPiece;
private Orientation orientation;
public RotationAction(Position positionOfPiece, Orientation orientation) {
this.positionOfPiece = positionOfPiece;
this.orientation = orientation;
}
public Position getPositionOfPiece() {
return positionOfPiece;
}
public Orientation getOrientation() {
return orientation;
}
}
So is there a better way to implement this or is this the best way to do this?
if
/else if
branches inBoard.execute()
into a method under theAction
interface. If it needs to mutate theBoard
directly, thenBoard
may need to grow new methods to accommodate that.Action myAction = new RotationAction()
), call the Action method on the resulting instance, and it would perform the custom action of the class you newed up (in my example, a Rotation action).