Previous Page
Next Page

3.2. Booleans

Name booleans after their associated test.

A special case can be made for subroutines that return boolean values, and for variables that store them. These should be named for the properties or predicates they test, in such a way that the resulting conditional expressions read naturally. Often that rule will mean they begin with is_ or has_, but not always. For example:


    sub is_valid;
    sub metadata_available_for;
    sub has_end_tag;

    my $loading_finished;
    my $has_found_bad_record;
 
    
# and later...
if (is_valid($next_record) && !$loading_finished) { METADATA: while (metadata_available_for($next_record)) { push @metadata, get_metadata_for($next_record); last METADATA if has_end_tag($next_record); } } else { $has_found_bad_record = 1; }

Again, explicit and longer names are strongly preferred. Compare the readability of the previous code with the following:

    sub ok;
    sub metadata;
    sub end_tag;

    my $done;
    my $bad;

    # and later...

    if (ok($next_record) && !$done) {               # Ok in what sense? What is done?
        METADATA:
        while (metadata($next_record)) {            # Metadata exists? Defined? True?
            push @metadata, get_metadata_for($next_record);
            last METADATA if end_tag($next_record); # Does this set an end tag?
        }
    }
    else {
        $bad = 1;                                   # What's bad? In what way?
    }

    Previous Page
    Next Page