Page 336 - Introduction to Programming with Java: A Problem Solving Approach
P. 336
302
Chapter 8 Software Engineering
if (first.matches("[A-Z][a-z]*"))
this.first = first;
else
System.out.println(first + " is an invalid name.\n" +
"Names must start with an uppercase letter and have" +
" lowercase letters thereafter.");
However, we like to use braces for all loop statements and if statements, even if there is only one enclosed statement. Why?
• Braces provide a visual cue for remembering to indent.
• Braceshelpyouavoidalogicalmistakeifyouaddcodelaterthat’ssupposedtobewithintheloopstate-
ment or the if statement.
The second point can best be understood with an example. Assume that a program contains this code:
if (person1.isFriendly())
System.out.println("Hi there!");
Assume that a programmer wants to add a second print statement (“How are you?”) for a friendly person1 object. A careless programmer might do it like this:
if (person1.isFriendly())
System.out.println("Hi there!");
System.out.println("How are you?");
Since the second print statement is not within braces, it is executed regardless of whether person1 is Apago PDF Enhancer
friendly. And do you want to ask an unfriendly person “How are you?” You might get a scowl for a response. On the other hand, if the program followed our style guidelines, the original code would look like this:
if (person1.isFriendly())
{
}
System.out.println("Hi there!");
Then if a programmer wants to add a second print statement (“How are you?”) for a friendly person1 object, it would be harder to make a mistake. Even a careless programmer would probably code the second print statement correctly like this:
if (person1.isFriendly())
{
}
System.out.println("Hi there!");
System.out.println("How are you?");
In our above discussion, we said that “we like to use braces for all loop statements and if statements.” More formally stated, we like to use a block for all loop statements and if statements. A block is a set of state- ments surrounded by braces.
Comments
As shown in Figure 8.1 and Figures 8.2a and 8.2b, for all but the shortest blocks, include a comment after a closing brace in order to specify the block that is being closed. For example, in Figure 8.2b, note this closing brace line for the setFirst method: