Conditionals Should Start on New Lines
What is it?
This practice is triggered when an if
statement is placed immediately after a closing brace }
of a previous conditional block on the same line. This style can create confusion and ambiguity in code readability.
Why apply it?
Placing conditionals on new lines enhances readability and maintains clear code structure, minimizing potential errors and misunderstanding for anyone maintaining the code.
How to fix it?
Ensure that each conditional statement starts on a new line. If conditions are exclusive, use else if
. Otherwise, if independent, visually separate them by starting new lines.
Examples
Example 1:
Negative
The negative example places two unrelated conditionals on the same line, leading to potential confusion.
if (isUserLoggedIn) {
displayDashboard();
} if (hasNotifications) { // Noncompliant
showNotifications();
}
Example 2:
Negative
The negative example uses two separate if
statements without proper elif structure for exclusive conditions.
if (temperature > 30) {
turnOnCoolingSystem();
} if (temperature < 18) { // Noncompliant
activateHeater();
} else {
maintainCurrentSettings();
}
Example 3:
Positive
The positive example separates unrelated conditionals onto new lines, reducing confusion.
if (isUserLoggedIn) {
displayDashboard();
}
if (hasNotifications) {
showNotifications();
}
Negative
The negative example uses poor formatting by including two separate conditionals for unrelated actions on the same line.
if (isStudentEnrolled) {
grantAccessToMaterial();
} if (hasLectureToday) { // Noncompliant
sendLectureReminder();
}
Example 4:
Positive
The positive example uses else if
for exclusive conditions, indicating clear control flow.
if (temperature > 30) {
turnOnCoolingSystem();
} else if (temperature < 18) {
activateHeater();
} else {
maintainCurrentSettings();
}
Example 5:
Positive
The positive example properly aligns conditions meant to be separate by starting each on a new line for unrelated logic.
if (isStudentEnrolled) {
grantAccessToMaterial();
}
if (hasLectureToday) {
sendLectureReminder();
}