View Full Version : Proper coding?

Mar 25, 2007, 05:37 PM
Hey guys,

I could use some insight in the following code..

- (IBAction)count:(id)sender
NSString *string = [[NSString alloc] initWithString:[textField stringValue]];
int i = [string length];
[labelField setStringValue:[NSString stringWithFormat:@"%@ has %d numbers",string, i]];
[string release];

So... A user types a message in the textField and when he clicks count, labelField shows a message with his original message and tells him the number of characters in the message. Very straight forward ( this is a challenge example from the book cocoa programming for os x that I am going through right now ).

What I'd like to know is if anyone would implement this differently.

Mar 25, 2007, 06:44 PM
You don't need to allocate and initialise a new string, as the -stringValue method returns an autoreleased string that you can use as is.

In fact, you don't need the string variable at all - a good rule of thumb is that variables are for things that vary. ;)

Finally, if this were a real project I would want to use a more descriptive name for the method.


- (IBAction)updateLabelField:(id)sender
[labelField setStringValue:[NSString stringWithFormat:@"%@ has %d numbers", [textField stringValue], [[textField stringValue] length]]];

Less code is better code. The best code is no code.

Mar 25, 2007, 06:59 PM
Incredible! Thank you so much.