|
|
|
|
|
by ajanuary
4913 days ago
|
|
Cheers for the counter-example. I agree there isn't really a sensible answer for [nil isEmpty]. There are two uses of isEmpty I can think of. if ([container isEmpty]) {
[container addItem:item];
}
We want to add an item to an empty container. If it's nil, we don't add an item to it; that seems okay. if (![container isEmpty]) {
Item item = [container getItemAt:0];
[item doSomething];
}
We check there will be an item before we get a value out of it. This one would cause issues.NSArray doesn't have an isEmpty method. I wonder if this is one of the reasons why, or if it's just something like wanting to keep the interface small. [Edit]
You can of course invert the logic. Using [container hasItems] in the two examples above would function just fine. While isEmpty seems to be the variant used everywhere, hasItems doesn't seem too unnatural. |
|
As for how you'd use it, I've pretty much always used it for early outs:
or for filling in caches: So it always ends up being tested positively. Or it does if you code like me, anyway :) (I make no statement about whether you should or not.)