if branch is empty
ID |
objectivec.correctness.empty_if_body |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Suspicious Code |
Language |
Objective-C |
Description
Reports an if or else if whose body holds nothing at all, whether the braces are written on one line or across several. A branch carrying a statement, or a comment explaining that the case is deliberately ignored, is not reported.
Rationale
An empty if evaluates a condition and then does nothing with the answer, which almost always means one of two things: the branch was emptied and the test was left behind, or the condition was written the wrong way round and the real work sits in the else. Both read as deliberate to the next person, because the condition is still there stating that this case matters. The negated-condition form is the more expensive mistake, since the body that does run is the one the author did not intend.
The following code illustrates the pattern detected by this rule:
@implementation Validator
- (void)checkOnOneLine:(NSInteger)code {
// FLAGGED: if branch is empty
if (code == 200) { }
}
- (void)deliver {
NSLog(@"delivering");
}
@end
Remediation
Fill in the branch, or delete the whole if if the case genuinely needs no handling. Where the shape came from wanting to act only on the negative case, invert the condition with ! and drop the empty branch. If ignoring the case is a real decision, record the reason in a comment inside the braces.