5

What's the point of the if statement in the following code:

- (NSArray *)myMethod
{
    NSArray *array = nil;
    if (!array) {
        array = [[NSArray alloc] initWithObjects...]
    }
    return array;
}

What's the point of the check if we assigned it to nil and what's the point of assigning it to nil if we didn't put anything inside of it?

Jessica
  • 153

1 Answers1

3

In terms of working code, you are correct, there is no point in checking for nil here. You could rewrite this as:

- (NSArray *)myMethod
{
    return [[NSArray alloc] initWithObjects...]
}

It is hard to know without seeing the entire codebase why this is being done. One possibility is that the original author expected to eventually replace myMethod with a call that potentially passed in a non-nil array or expected to eventually add more complex logic in the allocation.

The other very real possibility (and the most likely one in my opinion) is that whoever wrote it had an ingrained habit of always checking for nil and just wasn't thinking. Since this has no effect on the code, no one ever noticed, or could be bothered to fix.

Gort the Robot
  • 14,774
  • 4
  • 51
  • 60