in reply to isa() on any scalar
I want my node class to be inheritable, but ultimately, the "parent" of any object should at least be of type Node.
Personally, I don't like using class membership to determine whether an object is "ok" or not. I mean, someone could use Node as a base class, but override all the methods to do anything they want anyway, so what's the point of looking for it? I'd rather go with what is sometimes called duck typing. That is, if it walks like a duck, and talks like a duck, it must be a duck. In Perl terms, this means I like to use can to check if an object has the methods I am going to call on it. For example:
sub use_object_somehow { my ($obj, $foo, $bar) = @_; carp "Object doesn't quack right" and return unless $obj->can("foo") and $obj->can("bar"); $obj->foo($foo); $obj->bar($bar); }
This test is simple enough that I don't think it's too onerous to include in any subroutine that handles an incoming object, but it can be abstracted into a subroutine if so:
sub _check_obj { my ($obj, @methods) = @_; for (@methods) { return unless $obj->can($_); } return 1; }
Then it would be used like:
sub use_object_somehow { my ($obj, $foo, $bar) = @_; carp "Object doesn't quack right" and return unless _check_obj($obj, qw(foo bar)); $obj->foo($foo); $obj->bar($bar); }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: isa() on any scalar
by mrborisguy (Hermit) on Jun 10, 2005 at 18:32 UTC | |
by hv (Prior) on Jun 10, 2005 at 19:05 UTC | |
by revdiablo (Prior) on Jun 10, 2005 at 18:44 UTC | |
Re^2: isa() on any scalar
by shemp (Deacon) on Jun 10, 2005 at 18:10 UTC | |
by revdiablo (Prior) on Jun 10, 2005 at 18:41 UTC | |
by shemp (Deacon) on Jun 10, 2005 at 21:31 UTC | |
Re^2: isa() on any scalar
by tlm (Prior) on Jun 10, 2005 at 21:51 UTC | |
by revdiablo (Prior) on Jun 10, 2005 at 23:05 UTC |