Hack #36. Replace Bad Code from the Outside
Patch buggy modules without touching their source code.
Until computers finally decide to do what we mean, not what we say, programs will have bugs. Some you can work around. Others are severe enough that you have to modify source code.
When the bugs are in code you don't maintain and you don't have a workaround, Perl's dynamic nature can be an advantage. Instead of keeping local copies of externally managed code, sometimes patching that code from the outside is the simplest way to make your code work again.
The Hack
Imagine that you're building a large application that uses a hypothetical Parser module that, for whatever reason, calls exit( ), not die( ), when it fails. The relevant code might look something like:
package Parser;
sub parse
{
my ($class, $text) = @_;
validate_text( $shift );
bless \\$text, $class;
}
sub validate_text
{
my $text = shift;
exit 1 unless $text =~ /^</;
}
1;You might normally expect to use this module with code such as:
use Parser;
my $parser = eval { Parser->parse( 'some example text' ) };
die "Bad input to parser: $@\\n" if $@;However because of the exit( ), your program will end. It may be perfectly legitimate that the text to parse in this example is invalid, so Parser can't handle it, but the exit( ) is just wrong—it gives you no opportunity to alert the user or try to fix the problem. If validate_text( ) were a method, you could subclass the module and override it, but you don't have this option.
Fortunately, ...