On Mar 8, 2012, at 4:29 PM, Prime Coderama wrote:
> I have references to 'ground' and 'air' in multiple files. It is usually used
> in this context, but not always.
>> if ([transport.type isEqualToString:@"ground"]) {
>> // do something for automobiles
>> }
>> else if ([transport.type isEqualToString:@"air"]) {
>> // do something else for planes
>> }
>> else {
>> // we don't care
>> }
>
> Should I be using string constants to represent 'ground' and 'air' so if I
> ever change their literal, I just update it in one place? e.g.
>> NSString * const TransportGround = @"ground";
>> NSString * const TransportAir = @"air";
>
> I then decide I want to rename 'ground' to be 'wheels', then I would only
> update the above string constant.
I would say yes, partially so you only have one place to update it and
partially so you don't end up with typos, e.g., if ([transport.type
isEqualToString:@"gound"]).
Depending on your situation, subclassing could use the objects class to
indicate its type and reduce the number of if-elseif blocks.
Or you might try a typedef-ed enum instead of strings so you could use plain ==
for comparison. The typedef would also allow you to use switch statements so
that if you add a new transportation mode (e.g., water), you can get the
compiler to warn you if you aren't handling it (assuming you set the
appropriate flags and don't use a "default" case). However, you need to be
careful since Objective C typedefs aren't as carefully checked as C++ typedefs
(at least I don't think they are).
Aaron
_______________________________________________
Cocoa-dev mailing list ([email protected])
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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]