1

I usually return nil when there's no data to return. e.g.

- (MyObject *)myMethod:(MyParam *)param { MyObject *object = nil if (param ok and there is enough data to calculate on) { object = results of some calculations } return object; } 

But I got into a discussion with a colleague (a Java programmer and Object Orientation purist) who thinks this habit is error prone or at least yields a lot of conditional statements where one has to verify that returned data isn't nil. Where appropriate I also pass an NSError parameter along with param.

What's your take on this, is there a better cleaner way?

4
  • 1
    Dude Java is weird. Some of Apple's own classes do this, Ex: NSURL. Its standard practice for us. Commented Jan 31, 2014 at 9:02
  • duplicates: stackoverflow.com/questions/1274792/… and stackoverflow.com/questions/1626597/… Commented Jan 31, 2014 at 9:10
  • Yes, it is, @MdaG. NULL is "nothing" for any pointer type, and nil is "nothing" for object type (id). They're equivalent semantically (not to mention literally: nil == NULL). Commented Jan 31, 2014 at 9:31
  • 1
    @JoshCaswell Yes, but it's handled differently. You can send messages to nil, but you can't call a method on null. Doesn't that warrant a separate question as it gives options to how one can use nil? Commented Jan 31, 2014 at 10:51

2 Answers 2

3

Yes that's commonly done, even in C, using NULL or C++ using 0 or nullptr.

What's the alternative? Return some form in invalid object instance? That leads to just as many conditional statements calling object.isValid, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

The "invalid object instance" was the suggested replacement, but as you say, that also creates conditional statements.
2

OOP purists have "Null object pattern" in mind when object returning nil. It may make sense in some languages like JAVA where using null object raises exception but even there it creates more problems than it solves.
In objective c returning nil is what you should do because you can safely use even nil object if you know what you are doing (for instance calling [obj method] on nil object is safe).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.