Old Chestnut Example

Next

or, how things can go wrong if there isn't any kind of design-by-contract happening.

Maintaining an old system, you find something like this...

# Extract URLs for links out of a fragment of HTML.
sub link_extract {
    my ($self, $doc) = @_;
    my @urls;
    while ($doc =~ /"(.+?)"/g) {
        my $url = $1;
        push @urls, $url if ($self->is_urlish($url));
	# [imagine loads of unreadable other regexes here]
    };
    @urls;
};

"Eek! That's $(*&&!ing horrible!", you shriek, and refactor it to this:

    ...
    my $le = new HTML::LinkExtor;
    $le->parse($doc);
    my @urls = $le->links;
    foreach my $e (@urls) { $e = $e->[2] }; # Just the URLs please
    @urls;