Re: String Constants the solution
Re: String Constants the solution
- Subject: Re: String Constants the solution
- From: Andreas Grosam <email@hidden>
- Date: Wed, 14 Mar 2012 09:12:25 +0100
On Mar 9, 2012, at 1:29 AM, 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.
The more OO like approach is to create corresponding sub subclasses for class "Transport", e.g. AirTransport, GroundTransport, and possibly a factory class which creates such instances.
Each kind of transport instance defines its own behavior as needed. So, no need for
if ([transport.type isEqualToString:@"air"])
at all, just send a message like,
[transport doSomething];
Sure, it's possible that you may want to gather some input data first where you then decide upon those data which kind
of Transport instance you need to create. This could be for instance a property file which you read into your program, which has a key "transportType", whose value is a string, e.g. @"air". Then, when it comes to create the Transport instance, you reach the same original question. In this case you may want to define a set of NSString constants in that source file (not in the header file) which deals with reading input and creating Transport instances. That way, everything is nicely separated.
Andreas
_______________________________________________
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