dash2 has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a little set of modules to provide services for distributed computing/P2P networks. I want the modules to be as abstract as possible - they should be useful for different message formats and transports, although they have their own default format and transport.

There are 2 ways to achieve this:

1. Write a superclass with default methods for sending, receiving, encoding and decoding messages, and let subclasses override these methods. This is used by e.g. IO::Socket and HTTP::Daemon.

2. Write a class with optional callback hooks for the above tasks. Unless the hooks are defined (as subrefs) by the client, use the default methods. Something like this method is used by e.g. WWW::Robot.

Has anyone got any opinions on which is better, and when?

David

dave hj~

Replies are listed 'Best First'.
Re: subclass or hooks?
by dragonchild (Archbishop) on Nov 21, 2001 at 00:15 UTC
    How do you expect your classes to be used? That's the big difference between the two approaches.

    The first approach requires that I, your user, write a new class, test the whole class, and go forward from there. Lots of Perl knowledge required.

    The second requires that I, your user, write a funciton and pass the subref to you in some constrained fashion. Less Perl knowledge required, but slightly messier design (from an imperative standpoint).

    I personally prefer the second approach, because it's a better design for what you want to do. The extra time in design is well-worth the effort, IMHO.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      But if the number of hooks being specified gets large, then the other approach can be easier on the module user. So I say "Why not both?".

      For example, for each "hook" you could provide a default method that calls the user's hook if one has been specified, otherwise does the default processing. Then the user could override the hook either by registering a callback with the object or by defining a new class and overriding that method.

              - tye (but my friends call me "Tye")
        Better yet, the hooks themselves might be implemented in a subclass. I did this once in a project, and it worked beautifully.

        Applications were born as functions passed to a ...::Callback class. If the applications were used by many people or grew on popularity, they could become modules very easily. This also allowed for improved tests and better Q&A overall.

        Just my $0.02 :)