Re: String Constants the solution
Re: String Constants the solution
- Subject: Re: String Constants the solution
- From: Eeyore <email@hidden>
- Date: Thu, 08 Mar 2012 17:49:37 -0800
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@hidden)
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:
This email sent to email@hidden