Using Guard Clause

Categories: blog



Guard Clause, explained in Refactoring: Improving the Design of Existing Code (Chapter 9: Simplifying Conditional, Replace Nested Conditional with Guard Clauses), focuses on the key principle of refactoring: clarity.

A colleague of mine requested a function to validate the time format (10:00, etc). I quickly posted something on pastebin which looked like this.

sub valid_time{
    my ($time) = @_;

    # format kena betul. 10:00 ataupun 23:00
    if(!($time =~ m/([0-9]{2})\:([0-9]{2})/))
    {
        return 0;
    }

    my ($hour, $min) = split(/\:/, $time);
    if ($hour eq "" or $min eq "")
    {
        return 0;
    }

    if($hour > 23 or $hour < 0)
    {
        return 0;
    }

    if($min > 59 or $min < 0)
    {
        return 0;
    }

    return 1;
}

It was not as good as I expected. So I changed it a bit.

sub valid_time{
    my ($time) = @_;

    # format kena betul. 10:00 ataupun 23:00
    if(($time =~ m/([0-9]{2})\:([0-9]{2})/))
    {
        my ($hour, $min) = split(/\:/, $time);
        if (($hour eq "" or $min eq "")
            or ($hour > 24 or $hour < 0)
            or $min > 60 or $min < 0)
        {
            return 0;
        }
    }
    else
    {
        return 0;

    }

    return 1;
}

By using the Guard Clause, hopefully it is more readable.

sub valid_time{
    my ($time) = @_;

    # format kena betul. 10:00 ataupun 23:00
    if(!($time =~ m/([0-9]{2})\:([0-9]{2})/)){ return 0; }

    my ($hour, $min) = split(/\:/, $time);
    if($hour eq "" or $min eq ""){ return 0; }
    if($hour > 23 or $hour < 0){ return 0; }
    if($min > 59 or $min < 0){ return 0; }

    return 1;
}

I remembered that I read somewhere sometime ago, there should be only one exit point in a function, at first I thought it was a rule or something, apparently it is not.

One entry point is enforced by modern languages, and one exit point is really not a useful rule. Clarity is the key principle: if the method is clearer with one exit point, use one exit point; otherwise don't.

GimpStyle Theme design by Horacio Bella.