Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Perl OOP Function Entrance

by zakame (Pilgrim)
on Aug 29, 2017 at 03:05 UTC ( [id://1198233]=note: print w/replies, xml ) Need Help??


in reply to Perl OOP Function Entrance

At one point during my development of Hashids for Perl I thought about something like this, especially for some utility methods that I ported from the original JavaScript source. On one hand, there's a "seductive" thought of making all things OO-ish for a "consistent" interface, but ultimately I found that the utility methods were, after all, utility, and could be plausibly used out of the Hashids object context.

So in the end, I decided to make a Hashids::Util module that implements subs only, not methods; just add a bit of Exporter magic to provide the subs on by-name basis (or use Hashids::Util ':all' if you want them wholesale) and namespace::clean on both the module and requestors so that those subs don't pollute the namespace.

Here's a basic template for such a Util module that you might want to use:

package Util; use strict; use warnings; our ( @EXPORT_OK, %EXPORT_TAGS ); BEGIN { use Exporter 'import'; @EXPORT_OK = qw(foo bar baz quux); %EXPORT_TAGS = ( all => \@EXPORT_OK ); } # Dependencies for this Util module go here... use namespace::clean -except => [qw(import)]; sub foo { my ( $x, $y, @z ) = @_; ...; } sub bar { 42 } sub baz { ... } sub quux { ... } "Derp."; __END__
I suspect that another possible way for you would be to go implement those utility methods in a Role, and compose this Role in to your other classes; that might be a better fit for your situation, as you mention in another reply ("The base ideas was to create a class 'Object' which all classes inherit from.") We could turn the example above into something like this (assuming using Moo for OO, change needed if its something else:)
package Class::Util; use Moo::Role; sub foo { my ( $self, $x, $y, @z ) = @_; ...; } has bar => ( is => 'ro', default => sub { 42 } ); ...; 1;

Then in your classes you just add with 'Class::Util';.

EDIT: I realized you can actually combine the two approaches above rather easily (though at a cost of a bit of conceptual overhead.) Here's one rather naive approach:
package Class::Util; use Moo::Role; use Util (); for my $method (@Util::EXPORT_OK) { no strict 'refs'; *$method = sub { my $self = shift; my $sub = "Util::$method"; $sub->(@_); }; } "Derp.";

Now you can have a regular Util module for standalone subs, and a Class::Util role for objects.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1198233]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-03-29 11:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found