I just finished reading the "Functions" chapter from Uncle Bob's Clean Code. The main advice was to make sure that functions are short -- really short. And they should only do one thing per level of abstraction. Here's a function from an app I'm making to learn Cocoa (idea from Andy Matuschak).
- (IBAction)go:(id)sender
{
NSString *output = nil;
if ([[nameInputField stringValue] isEqualToString:@""])
{
output = @"Please enter your name";
}
else
{
NSString *date = [[NSDate date] descriptionWithCalendarFormat:@"%A, %B %d"
timeZone:nil
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
output = [NSString stringWithFormat:@"Hello, %@! Today is %@.", [nameInputField stringValue], date];
}
[responseOutputField setStringValue:output];
}
Basically, this function reads a name from a text field (nameInputField
) and outputs a message to another text field (responseOutputField
) I'm wondering a) if this function does 'one thing' per level of abstraction and b) how to make it shorter.