Skip to content

Commit

Permalink
Focus comments on the "dangling else" problem.
Browse files Browse the repository at this point in the history
  • Loading branch information
kjc authored and matyb committed Mar 23, 2018
1 parent 1cd8c1e commit bb1a863
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions koans/src/beginner/AboutConditionals.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,17 @@ public void basicIfElseIfElse() {

@Koan
public void nestedIfsWithoutCurlysAreReallyMisleading() {
// Why are these ugly you ask? Well, try for yourself
int x = 1;
boolean secretBoolean = false;
boolean otherBooleanCondition = true;
// Ifs without curly braces are ugly and not recommended but still valid:
// Curly braces after an "if" or "else" are not required...
if (secretBoolean)
x++;
if (otherBooleanCondition)
x = 10;
else
x--;
// Where does this else belong to!?
// ...but they are recommended.
assertEquals(x, __);
}

Expand All @@ -67,6 +66,8 @@ public void ifAsIntended() {
int x = 1;
boolean secretBoolean = false;
boolean otherBooleanCondition = true;
// Adding curly braces avoids the "dangling else" problem seen
// above.
if (secretBoolean) {
x++;
if (otherBooleanCondition) {
Expand All @@ -75,8 +76,6 @@ public void ifAsIntended() {
} else {
x--;
}
// There are different opinions on where the curly braces go...
// But as long as you put them here. You avoid problems as seen above.
assertEquals(x, __);
}

Expand Down

0 comments on commit bb1a863

Please sign in to comment.