Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Question regarding proper handling of a Hash/HashRef structure in Moose-variants

by haj (Vicar)
on Dec 22, 2021 at 08:22 UTC ( [id://11139824]=note: print w/replies, xml ) Need Help??


in reply to Question regarding proper handling of a Hash/HashRef structure in Moose-variants

I avoid to make HashRef attributes writable (and even making them readable can have surprising effects).

In your case, you seem to want to overwrite individual elements of limit by passing a hashref containing only the values you want to change. While the auto-generated attribute accessors of Moo* are very convenient for simple cases, I don't use them for complex attributes. I'd rather write a separate method like that:

sub new_limit { my $self = shift; my ($aggregation, $dimension, $val) = @_; # e.g. 'min', 'x', '-42' $self->limit->{$aggregation}{$dimension} = $val; }

That would, for example, allow to change the interna from aggregation-first to dimension-first without changing the external API.

Even if you want to allow many values to be changed in one go, I recommend not to use the auto-generated Moo* accessor, but to write a separate method which contains pretty much the same code which you used in your before modifier.

Replies are listed 'Best First'.
Re^2: Question regarding proper handling of a Hash/HashRef structure in Moose-variants
by NERDVANA (Deacon) on Dec 22, 2021 at 20:46 UTC
    I'll second this. The semantics expected by a random perl programmer are that

    $object->noun($value)

    has an implied verb of "set" which replaces the conceptual value of that attribute. If you want to apply changes to an attribute, you should make a method with a different verb in it, like apply_limit. You can then decide whether the attribute should even be exposed or not.

    For some variations on the theme, consider HTTP::Headers header($name, $value). That one acts sort of like your code, setting one of multiple headers, but it is understood that there is not one single attribute named "header", there are many headers given by name of the first argument, and you are setting one of them to a new value. If you were implementing HTTP::Headers in Moose, you would not declare 'header' as an attribute.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-19 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found