Tinier and Tinier Bits

We’ve all heard horror stories about long functions. I’m talking about ones with hundreds of lines of code; massive monolithic custom or one-off algorithms. I’ve seen them in the wild, particularly at one job that I won’t mention. This is nothing new. I’ve always thought they were horrible, at least since my first year or so as a professional.

For a long time, most of my functions and methods have been of moderate length. Maybe twenty to fifty lines. And I had always been fine with that, particularly if they are clear, well documented and internally consistent.

I am no longer fine with this length. In the past year I have changed my opinion to favour very short methods, no more than ten lines, and shorter than that is even better. The primary reason for this is because short methods lend themselves well to mixing and matching. They promote the re-use of logic instead of repeating logic. Plus with short methods, you don’t have much room to work, so you have to be more expressive and descriptive about what it is you are trying to accomplish. Instead of one long function to do validation of user input, saving, and redirecting, I would instead make four methods, one to act as gatekeeper, and then one each to do each of the validation, save, and redirect.

Here is an example in pseudocode:

bool update(object input[])
{
    // Validate
    bool success = true;
    foreach( var input in inputs )
    {
        if( !input.validate() )
        {
            success = false;
            break;
        }
    }

    // Save
    if( success )
    {
        var database = GetDatabase();
        try
        {
            inputs.foreach(x => database.write(x);
        }
        catch(DatabaseException e)
        {
            success = false;
        }
    } 

    // Redirect
    var nav = Page.getNavigation();
    if( success )
    {
        nav.redirect("somewhere good");
    }
    else
    {
        nav.redirect("somewhere not good");
    }

    return success;
}

This is easy enough to read, and relatively short, but by taking each block out, we can re-use each block in another algorithm, we get the benefit of changing the comments to the names of the new methods (removing useless comments in the process), and we can more easily see what the process for update() should look like. Let’s take a look at a new update method:


void update(object inputs[])
{
    bool success = validate(inputs);
    if( success )
    {
        success = save(inputs);
        if( success )
        {
            success = redirect(success);
        }
    }

    return success;
}

This is much more succinct. There are still improvements to be made of course. One of those is using an enum or some other form of return value so we know exactly what failed during the update.

One thought on “Tinier and Tinier Bits

Leave a Reply

Your email address will not be published. Required fields are marked *