Re: multiple definitions of compare: -- design flaw?
Re: multiple definitions of compare: -- design flaw?
- Subject: Re: multiple definitions of compare: -- design flaw?
- From: James Quick <email@hidden>
- Date: Fri, 11 Jul 2003 09:15:53 -0400
On Thursday, July 10, 2003, at 07:37 PM, Brent Gulanowski wrote:
I am going to try to clarify a little. Although I do like the idea of
putting a category on NSObject, now that I see how it would work.
I don't want to statically type because then I have to write more
code. I don't have to worry about type mismatches because I am
comparing something like this:
-(void)sortForKey:(NSString *)keyName {
[CustomObject setSortKey:keyName];
[myArrayOfCustomObjects sortUsingComparator:@selector(compare:)];
}
in my CustomObject class, I have this:
-(id)objectForKey:(NSString *)key {
return [myDictionary objectForKey:key];
}
-(void)compare:(id)other {
id value = [myDictionary objectForKey:sortKey]; // sortKey is a
global for the class
id otherValue = [other objectForKey:sortKey];
return [value compare:otherValue];
}
It's fairly neat and clean, no switches or if statements or typecasts.
Because the objects are the same class and the dictionary entries for
the same key are the same class, I know it's safe. I guess that it
could be argued that the dictionary entries could be screwed up, but
static typing won't solve that. For now I am just ignoring the warning
that results.
First, your compare: method must return a value, and is declared
(void).
I think you are confusing "neat, and clean" with short. Brevity, other
things being equal,
is a laudable goal. In this case, other things aren't equal, you are
sacrificing correctness
of the implementation and both reusability and brittleness of the
design in exchange for
a few lines of code. I don't consider that a fair trade.
You intend that the objects being compared are of the same class, and
assume they are.
This may currently be the case. But, neither you, nor the compiler,
can be sure that
this is true in some future runtime. For correct operation this method
*must* know for certain
that the objects have compatible behavior for their own compare
methods, but your code
does not check.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.