in reply to Re: OO-style modifiers for 'sub' ?
in thread 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.

All the tests that have been proposed so far work with inheritance. The inheritance problem is when the subroutine isn't called as a method.

C++/Java approach would be to define base classes (as interfaces) and inherit from them. The you can say

sub foo { my ($self) = @_; croak "..." unless ref($self) && $self->isa("AnInterface") }

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.

If you had a base class (or interface) it would be part of the class hierarchy. So you would have:

use base qw(AnInterface AnotherInterface YetAnotherInterface); sub foo { my $self = shift; ... code ... };

Which will be enough (as long as you call foo as a method) to ensure $self is of the appropriate class. Not verbose at all!

I've argued elsewhere that if you don't call foo as a method you deserve all you get :-)

So lets turn it around a bit:

sub foo # requires interfaces InterfaceA, InterfaceB { my ($self) = @_; InterfaceA::validate($self); InterfaceB::validate($self); }

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:

I'm covering the same ground as in Class::Interface -- isa() Considered Harmful - but surely these sort of relationships are exactly what ISA is all about?

I don't understand what the advantage of avoiding explicit inheritance is? I've yet to see an example that wouldn't (in my opinion) be better handled by ISA relationships or delegation.

Can somebody show me what I'm missing? :-)