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.
It sounds like it would be a good idea to define constants like you proposed, most likely in the
Transportclass.While consolidating it into a single location makes long term management easier, it can also help prevent errors that would arise if you happened to misspell one of those separate
@"ground"or@"air"instances.For example, if in one of the classes where you check the transport type and you accidently misspell
@"air"as@"iar", the code would not act as you expect, nor would you have any warning or error generated. By using defined constants, you have the help of the compiler to make sure you spell the defined constants correctly. For example, there’s no way you could spellTransportAirasTransportIar, as the compiler would issue an error when you tried to compile.