Problem of the Day
Wednesday, November 11, 2026
Problem:
Two software developers are working on a snippet of code that updates the x,y coordinates of an object depending on the value of a direction variable. Each programmer produces code that passes all tests.
Code 1, from Programmer 1
if (direction == 0) { xLoc++; }
else if (direction == 1) { yLoc++; }
else if (direction == 2) { xLoc--; }
else { yLoc--; }Code 2, from Programmer 2
if (direction == 0) {
xLoc++;
} else {
if (direction == 1) {
yLoc++;
} else {
if (direction == 2) {
xLoc--;
} else {
yLoc--;
}
}
}Which programmer's code is better, and why?
- Code 1 is better because it's shorter and takes up fewer lines in the source code
- Code 2 is better because it uses curly braces consistently throughout
- Code 1 is better because the conditions and increment statements are aligned vertically
- Code 2 is better because the nested nature of the
if-statements is more evident
The correct answer is c. That's my answer anyway, although there might be room for some reasonable disagreement! For a short series of similar conditions with a series of short, similar, bodies to be executed, using the whitespace of the page to line up the code provides a visual check on those instructions, a form of "defensive programming" that helps to avoid careless errors.
Fewer lines of source code can be a good reason, but less code should not be an overriding concern, especially where readability is concerned. There is something to be said for using curly braces consistently, although the indented if-else statements of Code 2 make it a little harder to verify that the structure is correct.