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?

MdaG
  • 2,680
  • 2
  • 34
  • 46
  • 1
    Dude Java is weird. Some of Apple's own classes do this, Ex: `NSURL`. Its standard practice for us. – Amar Jan 31 '14 at 09:02
  • duplicates: http://stackoverflow.com/questions/1274792/is-returning-null-bad-design and http://stackoverflow.com/questions/1626597/should-functions-return-null-or-an-empty-object – san Jan 31 '14 at 09: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`). – jscs Jan 31 '14 at 09: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? – MdaG Jan 31 '14 at 10:51

2 Answers2

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.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • The "invalid object instance" was the suggested replacement, but as you say, that also creates conditional statements. – MdaG Jan 31 '14 at 09:27
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).

Oleg Fedorov
  • 337
  • 3
  • 10