in reply to Interfaces
Well, I have an idea, but I've never really tried it out, so I don't know how practical it is. My idea is that the abstract base class can keep track of who is derived from it, and have an INIT block that checks to make sure all its derived classes define the appropriate methods. The INIT block is called after compilation is complete, but before program execution begins. A test implementation looked reasonable:
Abstract wants its subclasses to define swim and fly methods. If you define a class, say Fish, which inherits from Abstract and defines a swim method but no fly method, you get a fatal error at compile time:package Abstract; use Carp; my @inheritors; sub import { my $caller = caller; push @inheritors, $caller; } my @abstract_methods = qw(swim fly); sub INIT { my $bad = 0; for my $class (@inheritors) { for my $meth (@abstract_methods) { no strict 'refs'; unless (defined &{"${class}::$meth"}) { $bad=1; warn "Class $class inherits from Abstract, but does not define + $meth.\n"; } } } croak "Compilation aborted" if $bad; } 1;
Here's the Fish I used:Class Fish inherits from Abstract, but does not define fly. Compilation aborted at fish.pl line 0
Then test with perl -e 'use Fish'.package Fish; use Abstract; sub swim { "bloop bloop bloop"; } 1;
There are some problems with this implementation. For example, you might want some way to derive less-abstract classes from the abstract base class, and this implementation doesn't allow that. But I think the basic idea is sound.
The other thing that came to mind is that Damian Conway probably has something interesting to say about this. Have you checked his book?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Interfaces
by petemar1 (Pilgrim) on Apr 30, 2005 at 00:20 UTC |