What is the best way to assign a method body during the construction of Moose?

I use Moose(specifically MooseX::Declare) to create an iterator object Iterthat has a method nextthat promotes the state and returns 0or 1, as required for use in while. The problem I am facing is that, depending on the presence of one of the design parameters next, two very different sets of operations must be performed. As I can see, I have five options:

  • if ... then in nextmethod
  • subclass
  • sending hashes
  • character table manipulation
  • apply methods in different modules and load required during construction

Number 1 is just an amateur.

Number 2 , I suppose, is the right OOP way of doing things. I have no objection to this, but it seems to overdo it a bit to override one method.

I often used number 3 in the past when working procedurally or pseudo-functionally, and this is what I am doing now.

Number 4 , as we all know, is fraught with danger, and I know nothing about Moose Guts to want to start a mess when it is not needed.

The last element of number 5 seems to me the most reasonable (and Perlish), but, like Number 2, it is too much work. I am really wondering if there is a fifth way that I have not considered, for example, connecting to a metaclass or, possibly, a module MooseXthat is mature enough.

+3
2

"" subref :

has next => (
    isa => 'CodeRef',
    required => 1,
    traits => ['Code'],
    handles => { next => 'execute_method' },
);

'execute_method', "" , "" subref .

subref , , "next" :

has next => (
    # ...
    lazy => 1,
    default => sub {
         my $self = shift;
         return sub { ... } if $self->some_condition;
         # etc etc...
    },
);
+10

:

package Iter;
use Moose;
use Moose::Util qw(apply_all_roles);

has next_role => (is => 'ro');

sub BUILD {
    my $self = shift;
    apply_all_roles($self, $self->next_role);
}
0

Source: https://habr.com/ru/post/1780263/


All Articles