I find myself writing something like an event driven frame work, and I was pondering the various ways in which I've seen it done. It seemed to me, that the two main ways are "callbacks" and "interfaces".

Callbacks, of course, are obvious in what they do and how they work, and it's how most GUI Toolkits, such as tk, do things. You call some function and pass a coderef to it. Example:
sub called { print "You pressed a button!"; } my $button = new Button( name=>'foo', callback=>\&called );
The coderef passed to the constructor is derefenced when ever it's need to, and the call back is called.

The second way, which I've called "interface", although perhaps "inheritance" or some other word would better describe it, is how, for example, WxWindows does things. In this case, you don't call a function and pass a coderef to it, you simply implement a specific "interface" in your base class and then the other code uses this interface to interact with you. If that wasn't particularly clear, perhaps this example will help:
class MyButton; use Base 'Button'; sub on_click { print "You pressed a button"; } package main; my $button = new MyButton();
In this case you inherit the "other" methods, constructor, destructor, etc from a base class, then just implement the interface you wish to provide.

The pros and cons, as far as I can tell, is mostly that callbacks allow you to pass annonymous subs, or the same subref to multiple callbacks, but both of those are fairly minor pros, so this is what I ask you: Are there any other pros/cons I missed? Which do you prefer using? Why?

In reply to Event based programming: Callbacks or "Interfaces"? by BUU

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.