3 Program structure
This chapter covers
- Mistakes that often happen when using if-else chains
- Problems using
whileandforloops - 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 {
…
}