Use of goto statement
ID |
objectivec.maintainability.avoid_goto |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Control Flow |
Language |
Objective-C |
Description
Reports a goto statement, whether it stands alone or trails an unbraced if. A goto written inside a comment or inside a string literal is not reported.
Rationale
A goto breaks the correspondence between how the code is laid out and the order it runs in: the reader has to search the method for the label and then work out which of the jumps into it applies. In Objective-C the usual motive — one cleanup block for several failure paths — is already served by ARC, by an early return after releasing what the method owns, or by a small helper, so the jump buys nothing that costs the reader less.
The following code illustrates the pattern detected by this rule:
@implementation Parser
- (BOOL)parse:(NSData *)data error:(NSError **)error {
unsigned char *buffer = malloc(1024);
if (buffer == NULL) {
// FLAGGED: Use of goto statement
goto fail;
}
if (data.length == 0) {
// FLAGGED: Use of goto statement
goto cleanup;
}
// FLAGGED: Use of goto statement
if (data.length > 1024) goto fail;
cleanup:
free(buffer);
return YES;
fail:
free(buffer);
return NO;
}
@end
Remediation
Replace the jump with structured control flow: an early return for a guard, a break or continue for a loop, or a helper method holding the shared tail. Where the label ran manual cleanup, move the owned resources under ARC or release them in the one place the method returns from.