On Feb 27, 2013, at 13:12 , Brad O'Hearne <br...@bighillsoftware.com> wrote:

> - (id)init:(NSError **)error;
> {
>    self = [super init];
> 
>    if (self)
>    {
>        if ([self operationThatMightFail:error])
>        {
>            *error = nil;
>        }
>        else
>        {
>            return nil;
>        }
>    }
> 
>    return self;
> }

The 'init' method pattern that returns nil and an error object works just fine 
for me. FWIW, I've adopted the convention (for all my code, though of course 
the frameworks APIs don't necessarily work this way) that an init method 
*either* doesn't return nil:

        - (id) init {
                self = [super init];
                NSAssert (self, @"Initializer failed"); // <-- if super's init 
isn't code I wrote; if it is I just leave this assertion out
                …
        }

*or* has an error parameter similar to your example. The advantage of this 
approach is that it eliminates a lot of trivial checking for nil returns in the 
caller, which has to create an error object anyway in order to get the error 
presented to the user, but doesn't know what the error really was. 

However, your code isn't quite right:

-- It's not necessary to set the output error value unless you return nil. 
According to the usual pattern, callers should *not* expect anything in *error 
(especially nil) if the method succeeded.

-- The usual pattern lets the caller specify NULL for the error parameter. If 
you set the output value explicitly, you'd be wise to check for that.

Applying those 2 things to your code, you get this:

       if ([self operationThatMightFail:error]) // <-- rely on this to check 
for error==NULL properly
                return nil;

which is a whole lot more concise.

P.S. I agree with John's statement that a factory method is better (especially 
with ARC) for your class's public interface, but even within the class 
implementation you might not be able to avoid the need to return an error from 
a private 'init'.

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to