Call of the callback: Inversion of Control or just coolness?

Suppose I have a Runner which holds a Prober object. I need the Runner to call the Prober and update stuff according to the result. Pretty simple, right?


my $prober = Prober->new(...);
my $result = $prober->check;
if ( $result eq 'whatiwant' ) {
$self->update($stuff);
}

However, I'm running in asynchronous mode, which means I need the prober and update to run somewhere in the loop, and I can't just sit around and wait for a reply. I gotz otha dingz to do, mon! So, I have two options:

- I call the Prober and sends it the Runner object ($self to you). Once the Prober is done, it will call the correct update method in the Runner object object.
- The Runner calls the Prober and sends it a callback containing updating code.

I asked around at $work and had been suggested to use the first method. Instead, I actually went for the second. (let this be a lesson to you: always listen to suggestions, but make up your mind youself!)

What I didn't like about the first method is that I'm sending the entire Runner object to a very small intermediate object. Felt kind of dirty. But, the more I thought about it, I noticed there was something else I didn't like about it. I'm basically putting a lot of Runner object into the Prober. That's not right...

By sending a callback to the Prober instead of the entire Runner object, I gain the following:
- The Prober doesn't need to know about any object other than itself. It doesn't know what you send it (other than a callback), not does it care.
- If I need to change the updating code, I only need to change what I send the Prober. I never need to change the Prober itself, it remains exactly the same.
- I can send a lot of other stuff as well, not just updating code.

In my case I could even set this callback on the initialization of the Prober object. This is how it would look:

Prober->new(
...
on_change => sub {
$self->log("Updating...");
$self->update($stuff); # suppose this is curried method from $self->updater
},
);

How cool is that? Very cool!

It would be much cooler though if I could present this situation to you in an interesting way, such as how Tom Wyant does it. Damn, I'm jealous! I'll try though!

1 Comment

Hey - you had me at the Jack London title. "Perl of the Frozen North?" "Sergeant Perlston of the Yukon and his Wonder Dog Yukon King (arf! arf!)"? The mind boggles.

Leave a comment

About Sawyer X

user-pic Gots to do the bloggingz