On Jul 1, 2009, at 6:32 AM, Patrick Mau wrote:

Since NSComparisonResult is an ordered enum typedef, I'd like to know if it's safe to write
the following code to test for 'greater or equal to':

// This would cover both NSOrderAscending and NSOrderSame
if ([obj1 compare:obj2] < NSOrderDescending) {
        // code
}

instead of testing for both constants:

// This makes both tests explicit
if (([obj1 compare:obj2] == NSOrderAscending) || ([obj1 compare:obj2] == NSOrderSame)) {
        // code
}

In practical terms, it should be safe. Certainly, the specific values of the existing enum elements can't change. That would be a binary incompatible change.

The other possibility to consider is new elements being added to the enum, but I can't conceive of Apple doing that, either. First, "same", "ascending", and "descending" seem to cover all the bases of a comparison result. :) Second, there's undoubtedly lots of code which assumes all negative values mean ascending and all positive values mean descending. The particular construction you used ("< NSOrderDescending") seems odd to me, but "< NSOrderSame" or "<= NSOrderSame" are probably relatively common.

The oddness of "< NSOrderDescending" seems like the best argument against using it, to me. It's far from clear when reading that code exactly what its semantics are, without consulting the enum definition. The explicit test is much clearer, although I'd extract the duplicate invocation of -compare: to a separate variable so as to only do it once (and make it clear that you're testing the same thing each time). The best of all worlds seems to be the simpler "!= NSOrderDescending".

Regards,
Ken

_______________________________________________

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

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

Reply via email to