chapter three

3 Program structure

 

This chapter covers

  • Mistakes that often happen when using if-else chains
  • Problems using while and for loops
  • How to avoid the pitfalls around the initialization of fields and classes
  • Missing call to a superclass method
  • What happens if you accidentally declare a static field instead of instance one

Java provides a number of constructions to alter the program control flow. This includes branching statements (switch, if-else), loop statements (for, while) and so on. Programmers tend to make many mistakes in control flow statements that may result in visiting the wrong branch, not visiting the desired branch, having more loop iterations than expected, and so on.

Another class of mistakes discussed in this chapter comes from the errors in program structure outside of the method body, like incorrect initialization order or accidental use of the static modifier where it should not be used.

3.1 Mistake #15. Malformed if-else chain

One of the common patterns in Java programming is an if-else chain that allows you to perform different actions depending on multiple conditions, like this:

if (condition1) {
  …
}
else if (condition2) {
  …
}
else if (condition3) {
  …
}
else if (condition4) {
  …
}
else {
  …
}

When this chain is quite long, it sometimes happens that one of the intermediate else keywords are missing:

if (condition1) {
  …
}
else if (condition2) {
  …
}
if (condition3) {
  …
}
else if (condition4) {
  …
}
else {
  …
}

3.2 Mistake #16. Condition dominated by a previous condition

3.3 Mistake #17. Accidental pass-through in switch statement

3.4 Mistake #18. Malformed classic for loop

3.5 Mistake #19. Not using the loop variable

3.6 Mistake #20. Wrong loop direction

3.7 Mistake #20. Loop overflow

3.8 Mistake #21. Idempotent loop body

3.9 Mistake #22. Incorrect initialization order

3.9.1 Static fields

3.9.2 Subclass fields

3.9.3 Class initialization order

3.10 Mistake #23. Missing super method call

3.11 Mistake #24. Accidental static field declaration

3.12 Summary