Wednesday, August 28, 2013

Cocoa NSError Conventions

Cédric Luthi:

Follow Cocoa conventions for methods without parameters returning errors, i.e. xxxAndReturnError:(NSError **)error instead of just xxx:(NSError **)error.

The Cocoa APIs are inconsistent and use both patterns. Sometimes the error parameter is an NSError, other times an NSDictionary.

I dislike the ambiguity of -save: and the verbosity of -saveAndReturnError: (which, incidentally, returns a BOOL), so in my own code I’ve been using names like -saveError: (which has its own problems…).

8 Comments RSS · Twitter

xxxAndReturnError is wrong anyway, because the whole point of an error is that it's xxxOrReturnError. (Although I say this after abusing NSError in an app a few weeks ago so it can return a partially constructed object…but anyway.)

You could think about a verb, how about saveOrErr:?

uh, `saveWithError:` ?

@Nicholas Why the “Err”?

@charles Because “with” makes it sound like an input parameter.

@Nicholas Oh, that makes sense now. I kind of like that. For some reason I kept thinking of OSErr.

Happened to me. When I NSErrorized (… OK, might not be the most elegant term) the iOS Objective-C playback API I was in charge of, I had not problem with, say, - (BOOL)jumpAt:(float)pos error:(NSError**)err;, but I did something like - (BOOL)playError:(NSError**)err; (or maybe - (BOOL)play:(NSError**)err; ? I can't remember, but either way) and it looked like you were trying to play the error double pointer var, as a result my colleague rightly called me out on it (even though he is not versed in iOS), so I went looking for an example in the Cocoa frameworks and found the somethingAndReturnError: pattern which I have happily applied: - (BOOL)playAndReturnError:(NSError**)err;. For me, it is the standard to follow.

I haven't used it in any code, but an idea would be "reportingError:" which can work as both a verb and noun phrase as in:

- (BOOL)playReportingError:(NSError **)error;
- (BOOL)playSong:(Song *)song reportingError:(NSError **)error;

Leave a Comment