Correct Structure to check for Errors using NSError

前端 未结 4 1823
囚心锁ツ
囚心锁ツ 2021-02-02 01:59

I\'m coding up various routines and I\'m trying my best to keep it neat and refactored.

Methods I\'m creating are starting to look similar to this code:

         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 02:37

    The gist of your question is whether there are structural improvements you can make to your error handling. I think so, by essentially introducing more layers of nesting, either by extracting more code into separate methods/functions, or by introducing nesting in your high level sample method.

    The idea is, when it comes to handling most errors, you probably are either interested in performing an alternate task, or in failing and propagating the error up the chain so that some responsible controller can convey the error to the user through UI.

    Using this idea of "propagate or handle", I would rewrite your sample method like this:

    -(IBAction)buttonPress:(id)sender {
    
        // Create Document Shopping List with this document
        [self doSomething:&error];    
        if(error == nil) {
            [self doSomethingElse:&error];
            if (error == nil) {
                [self doYetSomethingElse:&error];
            }
        }
    
        if(error) {
            [NSApp presentError:&error];
        }    
    }
    

    Note that there are good arguments against introducing too much nesting in a particular method. Nesting such as this is essentially a short alternative to extracting methods. It might make more sense, for instance, that "doSomething:" itself calls doSomethingElse:, which calls doYetSomethingElse: for instance. This would impose the same structure on the code as the if-nest, but would be arguably more maintainable.

    As an aside, I am not a fan of inline return statements. In this particular instance, the sample method doesn't actually call for a return value, but if it did, I prefer to set a local variable to the returned value and only return at the end of the flow control. Jumping out of a function or method prematurely is a sure way to encounter weird bugs, IMHO.

提交回复
热议问题