C++/Java approach would be to define base classes (as interfaces) and inherit from them. The you can say
But this would have problems: First, you may need to check multiple interfaces; second you have to include them in your ISA list; third, its all getting very verbose, and not-Perl.sub foo { my ($self) = @_; croak "..." unless ref($self) && $self->isa("AnInterface") }
So lets turn it around a bit:
This client code is much simpler: you are passing the implementation of the check down to a module that knows what it means to be that module. An you no longer require explicit inheritance:sub foo # requires interfaces InterfaceA, InterfaceB { my ($self) = @_; InterfaceA::validate($self); InterfaceB::validate($self); }
Ignoring the issue of naming, it is clear that having an interface know what methods are needed is more powerful than requiring explicit inheritance. If an object supports all the methods in an interface, then it can be said to implement that interface.sub InterfaceA::validate { my ($candidate) = @_; error unless ref($candidate); error unless $candidate->isa("InterfaceA"); # explicit ISA } sub InterfaceB::validate { my ($candidate) = @_; error unless ref($candidate); error unless $candidate->can("fn1"); # implicit ISA error unless $candidate->can("fn2"); }
One last thing: the names I've chosen are non-optimal, but if validation is common then you'd think that you want concise names. But you can work around this. We might name our validation methods "is_implemnted_by", and create a wrapper function (in a shared utilities module):
--Davesub validate_object { my ($self, @interfaces) = @_; error unless ref($self); foreach my $interface (@interfaces) { my $fn = $interface . "::is_implemnted_by"; error unless $fn->($self); } } #... sub foo { my ($self) = @_; validate_object($self, qw/InterfaceA InterfaceB InterfaceC/); } sub bar { my ($self) = @_; validate_object($self, map {"Interface$_"} qw/A B D/); }
In reply to Re: OO-style modifiers for 'sub' ?
by dpuu
in thread OO-style modifiers for 'sub' ?
by Gilimanjaro
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |