in reply to OO-style modifiers for 'sub' ?
As other people have pointed out, checking that you are a specific type is just not-Perl. In fact, its not OO either, because it disables inheritance.
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/); }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: OO-style modifiers for 'sub' ?
by Aristotle (Chancellor) on Jan 24, 2003 at 23:59 UTC | |
Re^2: OO-style modifiers for 'sub' ?
by adrianh (Chancellor) on Jan 26, 2003 at 23:53 UTC | |
by dpuu (Chaplain) on Jan 31, 2003 at 18:41 UTC | |
by adrianh (Chancellor) on Jan 31, 2003 at 22:38 UTC | |
by dpuu (Chaplain) on Feb 01, 2003 at 00:37 UTC | |
by adrianh (Chancellor) on Feb 01, 2003 at 22:16 UTC | |
Re: Re: OO-style modifiers for 'sub' ?
by l2kashe (Deacon) on Jan 27, 2003 at 06:32 UTC | |
by Aristotle (Chancellor) on Jan 27, 2003 at 11:14 UTC |
In Section
Meditations