DEV Community

kobaken
kobaken

Posted on

Release: Function::Interface

I'm developing Function::Interface, this module provides a typed interface like Java interface.
At compile time, check if the abstract functions are implemented.

You can see the demo in the following capture:

asciicast

USAGE

Declare typed interface package IFoo:

package IFoo {
    use Function::Interface;
    use Types::Standard -types;

    fun hello(Str $msg) :Return(Str);

    fun add(Int $a, Int $b) :Return(Int);
}
Enter fullscreen mode Exit fullscreen mode

Implements the interface package IFoo:

package Foo {
    use Function::Interface::Impl qw(IFoo);
    use Types::Standard -types;

    fun hello(Str $msg) :Return(Str) {
        return "HELLO $msg";
    }

    fun add(Int $a, Int $b) :Return(Int) {
        return $a + $b;
    }
}
Enter fullscreen mode Exit fullscreen mode

It is good not to depend on the implementation:

package FooService {
    use Function::Interface::Types qw(ImplOf);
    use Function::Parameters;
    use Function::Return;
    use Mouse;

    use aliased 'IFoo';

    fun greet(ImplOf[IFoo] $foo) :Return() {
        print $foo->hello;
        return;
    }
}
Enter fullscreen mode Exit fullscreen mode
my $foo_service = FooService->new;
my $foo = Foo->new; # implements of IFoo

$foo_service->greet($foo);
Enter fullscreen mode Exit fullscreen mode

How it works

To explain briefly

  1. The keywords fun andmethod for declaring abstract functions are implemented in Keyword::Simple and PPR. B::Deparse shows that it stores meta information of abstract functions.

  2. In order to check whether the interface is correctly implemented, the stored interface meta information is compared with the implementation meta information that can be obtained using Function::Parameters and Function::Return.

Finally

Have you ever experienced the software becoming bigger and less maintenance? In such a case, I think it is important to divide the code, make it easy to change, and make code easier to read.

In order to divide the code, I think the interface is useful.
Please try it!!

Thanks.

Top comments (0)