Pistol
Pistol

Reputation: 326

Is there an OO Perl equivalent to an interface?

I know with OO Perl I can have objects and inheritance, but are interfaces implemented? If so, how are they enforced?

Upvotes: 9

Views: 2073

Answers (4)

user4197534
user4197534

Reputation: 11

interfaces are needed because the language does not support

Interface is a OOP concept. They are not needed due to a technical issue.

Upvotes: 1

Dave Pirotte
Dave Pirotte

Reputation: 3816

But of course! Class::Interface.

That said, I'd look at Moose first. It is fantastic.

Upvotes: 10

Chas. Owens
Chas. Owens

Reputation: 64909

You can create a pure virtual class (or role if you are using Moose or MooseX::Declare):

package Foo;

use strict;
use Carp;

sub new  { croak "new not implemented" };
sub do_x { croak "do_x not implemented" };
sub do_y { croak "do_y not implemented" };

But the enforcement will be at run-time. In general, interfaces are needed because the language does not support multiple inheritance and is strictly typed. Perl supports multiple inheritance and (using Moose) something like multiple inheritance (but better) called roles and it is dynamically typed. The strict vs dynamic typing comes down to duck typing (if it quacks() like duck, walks() like a duck, and swims() like a duck, then it is a duck). In Perl, you say:

if ($some_obj->can("quack") {
    $some_obj->quack;
} else {
    croak "incompatible class type: ", ref $some_obj;
}

Upvotes: 17

ijw
ijw

Reputation: 4526

In traditional Perl OO, very little is enforced. You have the option of $obj->can('methodname') to duck-type what you're using, but there's nothing much like an interface.

(But have a look at Moose, the Roles in there may be what you're after.)

Upvotes: 11

Related Questions