Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ideas from Uncle Bob's Clean Code in real-world code

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.

like image 812
jasonbogd Avatar asked May 10 '26 02:05

jasonbogd


1 Answers

I disagree that this function is at the right level. The core computation of working out what to output based on current input should be factored into another function. This will make that computation much more testable (since you don't need any text fields, you can unit test in isolation) and reusable, since it has much less contextual baggage. As it is, the function is hard-wired to a specific use and so is not reusable.

As it is, how do you test it without actually running the application?

like image 118
mdma Avatar answered May 12 '26 12:05

mdma