Problem of the Day
Wednesday, November 18, 2026
Problem:
In order to print out an 11 × 21 rectangular grid of dots (".") with a "+" at the center, two programmers each come up with their own solution.
Code 1 from Programmer 1
for (int row = 0; row < 11; row++)
{
for (int col = 0; col < 21; col++)
{
if (row == 5 && col == 10) // middle of 11 x 21 area
System.out.print("+");
else
System.out.print(".");
}
System.out.println(); // go down to next row
}
Code 2 from Programmer 2
final int HEIGHT = 11;
final int WIDTH = 21;
for (int row = 0; row < HEIGHT; row++)
{
for (int col = 0; col < WIDTH; col++)
{
if (row == HEIGHT / 2 && col == WIDTH / 2)
System.out.print("+");
else
System.out.print(".");
}
System.out.println(); // go down to next row
}
Which programmer's code is better, and why?
- Code 1 is better because it has fewer lines of code
- Code 2 is better because it uses constants for the grid dimensions
- Code 1 is better because it minimizes the use of identifiers
- Code 2 is better because it got rid of an unnecessary comment
The correct answer is b. Although both programs work identically, Code 2 is easier to understand and maintain. It gets rid of the "magic numbers" 11 and 21 in favor of clear identifiers HEIGHT and WIDTH, and allows us to calculate the center of the grid rather than having to hard code the center using more magic numbers.
Also, the programmer can more easily modify the code (if needed) by changing HEIGHT and WIDTH at a single point in our code, rather than having to search through the program trying to find where we might have used the magic numbers.
Using constants to avoid the use of magic numbers is another example of defensive programming: writing your code so that debugging it and maintaining it is more efficient and less prone to error.