tags:

views:

38

answers:

2

I wonder if anyone could help me with a design/layout question. If you come to a point in your code where you want to stop execution and return an error how do you approach cleaning up? do you simply duplicate that code as I have done here, or is there another way?

    if(fileContents == nil) {
        NSLog(@"ReadError: %@", [fileError localizedDescription]);
        [pool drain];
        return 1;
    } else {
        NSLog(@"Success  : %@", fileContents);
    }

    // Clean up
    [pool drain];
    return 0;
}
// END

gary

+3  A: 

For exactly your case it is easier to introduce variable named "result".

    int result = 0;
    if(fileContents == nil) {
        NSLog(@"ReadError: %@", [fileError localizedDescription]);
        result= 1;
    } else {
        NSLog(@"Success  : %@", fileContents);
    }

    // Clean up
    [pool drain];
    return result;
}
// END
RocketSurgeon
+1  A: 

I use a similar approach to RocketSurgeon except that I use it as a running "everything is ok" flag. That way I can set ok to false at any point, skip any further code, but still have all the relevant cleanup (including frees in C, as shown) at the end.

bool ok = true;
type *someptr = 0;

if (ok)
{
    if ((someptr = (type *)malloc(...)) == NULL)
    {
        // report error
        ok = false;
    }
}
if (ok)
{
    if(fileContents == nil)
    {
        NSLog(@"ReadError: %@", [fileError localizedDescription]);
        ok = false;
    }
    else
    {
        NSLog(@"Success  : %@", fileContents);
    }
}

// Clean up
if (someptr)
    free(someptr);
[pool drain];
return ok;
Tom
Thats certainly one way to go, just curious you are returning 1 (true) in main() rather than 0 on success or non-zero for error?
fuzzygoat
No, this was just a quick example. In general I'd either try to return a useful error code or just do "return ok ? 0 : 1"
Tom