This is part of a brief series on Good Habits For Java Programmers.
Yes, it's true, you don't need curly braces to introduce a scope for a bit of Java such as
if (isValid)
System.out.println("The input is valid.");
or even for
if (isValid)
System.out.println("The input is valid.");
else
System.out.println("The input is not valid.");
But it's dangerous and introduces style inconsistencies not to.
The danger
The danger comes from the fact that it's far too easy to add a second thing to do when those if
or else
conditions are met and not realize you need to now add the curly braces to make sure both things are done when the condition is met. Consider
if (isValid)
System.out.println("The input is valid.");
System.out.println("It sure is."); // This will always execute, even if isValid is false.
Oops. That second line will always execute, regardless of the whether isValid
is true
or false
. The author probably wanted to add curly braces:
if (isValid) {
System.out.println("The input is valid.");
System.out.println("It sure is."); // This will only execute if isValid is true.
}
Similarly for
if (isValid)
System.out.println("The input is valid.");
else
System.out.println("The input is not valid.");
System.out.println("It sure isn't."); // This will always execute, even if isValid is true.
The author probably wanted to add curly braces:
if (isValid) {
System.out.println("The input is valid.");
} else {
System.out.println("The input is not valid.");
System.out.println("It sure isn't."); // This will only execute if isValid is false.
}
Style consistency
A lot of our ability to read programs easily comes from the authors' obeying conventions and their being consistent in their coding style.
For example, if a file is formatted inconsistently with different indentation patterns everywhere, it's hard to take in. You wouldn't want to read this:
// Don't do this!
if (isValid) {
System.out.println("The input is valid");
} else {
System.out.println("The input is not valid");
System.out.println("It sure isn't");
}
Sometimes adding curly braces for if
statements and sometimes not introduces inconsistency. Always using braces introduces consistency, and consistency increases readability and maintainability. The less work we have to do when understanding a program, the better.
Top comments (0)