if / else-if chain has no final else clause
ID |
objectivec.maintainability.if_else_chain_without_else |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
Objective-C |
Description
Reports an if / else if chain of braced branches that ends without a final else. The finding is placed on the last else if of the chain, the one a final else would follow. Both the } else if (…) { and the Allman layouts are recognised; a chain written without braces is not.
Rationale
A chain of conditions with no final else handles the cases it names and silently does nothing for every other value. Nothing distinguishes the two situations at the call site: a method that returns without acting looks exactly like one whose work was not needed. The omission also decays over time - when a new state, error code or enumeration constant is added later, every chain written before it exists takes the do-nothing path, and no compiler warning marks the places that need a new branch.
The following code illustrates the pattern detected by this rule:
@implementation Router
- (void)routeTwoWay:(NSInteger)code {
if (code == 200) {
[self ok];
// FLAGGED: if / else-if chain has no final else clause
} else if (code == 404) {
[self notFound];
}
}
@end
Remediation
Add a final else. Where the remaining cases really are meant to do nothing, say so in the else with a comment or a log line, so the next reader can see the omission was deliberate; where they should not happen at all, NSAssert or a logged error there turns a silent fall-through into something a test or a crash report will show.