|
|
|
|
|
by jrockway
5534 days ago
|
|
Wait, I spend 99% of my time programming in dynamic languages, and I still use dependency injection. Why would I want to resort to hacks when I can just pass stuff in to my classes instead? I will admit that I need the hacks from time to time, though. Recently, I wrote an overly large method that calls a callback when the command completes. For my test, I needed to run a bit of code right before the callback was called. Runtime role application to the rescue! In my test, I wrote: my $done = AnyEvent->condvar;
$done->begin;
my $called_callback = 0;
{ pacakge FixupCallback;
requires 'update_table';
around 'update_table' => sub {
my ($orig, $self, @args) = @_;
my $cb = pop @args;
# this is like "super"
$self->$orig( @args, sub {
$called_callback = 1;
$cb->(@_); # call the original callback
$done->end; # then return control flow back to us
});
};
}
Then, I just find the instance of the class that I need to tweak: my $view = $app->latency_publisher->view;
FixupCallback->meta->apply($view);
And now I've fixed up the code enough to write a sane test. While cool, this doesn't negate the need for dependency injection. I want my app code to be 99% clean, and use the hacks for that 1% case where the hacks result in cleaner code than "the right way".Also, I've never programmed Java or C#, so don't say that I have inherited bad habits from those languages :) |
|