Objective C has a concept of a nil object which would accept any method call with any parameters without complaining and silently return another nil.
I have used something similar in Java using easymock and mockito for testing. Is there something similar for main line code? Is it even a good idea to have something like this?
One use-case where I am considering using it is with optional metrics. We have codahale metrics counters on which we call mark() every time an event is generated. This is surrounded by an If/then to check for metrics enabled flag. I could just use a nil object as counter and silently accept the mark call if metrics are not enabled.
nilis not an object -- it's a pointer that doesn't point to anything. The language happens to be defined such that it's (often) legal to send messages tonil, butnildoesn't represent an object. (Of course, there's also[NSNull null], which is an object.)nil. Some other objects don't like havingnilas a message parameter.nilis always legal, using the returned value may not be, so while legal it may nevertheless be an error. As you point out, some methods may not likenilas a parameter. E.g.[[NSString alloc] initWithString:[foo name]]will throw an exception if foo isnilbecause[foo name]will return nil. Sending-nametofoois legal, but that's not much comfort to the user who wonders why your app just crashed.