You haven't said what you want to happen if the direction isn't any of those values. Maybe that's currently the full set of directions, but in the future it may not be - and fundamentally the Java compiler doesn't check that you've covered every enum possibility. (You're also missing break
statements, as noted by other answerers.)
Personally I'd change the approach and get rid of the switch
entirely: add a toChar
method to Direction
, and then you can just use:
return Integer.toString(RoboID) + direction.toChar();
Your enum constructor would take the character to use as well, so it would be very easy to implement.
Much cleaner, IMO. The only downside is that it ties your character representation to the Direction
enum which may be intended to be UI-neutral. If that's the case, I'd have a Map<Direction, Character>
instead, and you can use it very simply:
return Integer.toString(RoboID) + DIRECTION_CHARS.get(direction);
If you want to stick with the switch
statement, I wouldn't add an initial value to the variable as others have suggested - I'd throw an exception in the default
case:
@Override public String toString() {
char dirArrow;
switch (direction) {
case UP:
dirArrow= '^';
break;
case RIGHT:
dirArrow= '>';
break;
case DOWN:
dirArrow= 'V';
break;
case LEFT:
dirArrow= '<';
break;
default:
throw new IllegalStateException("Unexpected direction! " + direction);
}
return (Integer.toString(RoboID) + dirArrow);
}
That's assuming it really isn't valid to have a direction
other than the ones you've listed. Now, if you add a direction and forget to update this method, you'll end up with an exception rather than silent bad data.
The reason to not use a "dummy" initial value for the variable is that it doesn't express your desired behaviour. If you were to describe the method to someone in words, you would never mention that value, unless you really have a default value (e.g. space), in which case it's absolutely the right way to go.