Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are of course a lot of ways to combine a bunch of values into a more complex value -- that's basically what the study of data structures is about. What particular data structures to choose is a fairly involved question, highly dependent on your actual use cases.</p> <p>I know fairly little about your case, but the thing I've gleaned from your question that all of these attributes represent similarly-structured concepts. And so I would create a new data type, the <code>Scale</code>:</p> <pre><code>use MooseX::Declare; class Scale { for (qw/min max def/) { has $_ =&gt; (is =&gt; 'ro', isa =&gt; 'Num', required =&gt; 1); } has val =&gt; (is =&gt; 'rw', isa =&gt; 'Num', lazy_build =&gt; 1); method _build_val() { return $self-&gt;def; } method BUILD($args) { confess "Out of range!" unless $self-&gt;_is_in_range($self-&gt;val); } method _is_in_range($val) { return defined $val &amp;&amp; $val &gt;= $self-&gt;min &amp;&amp; $val &lt;= $self-&gt;max; } before val ($new_val?) { return unless defined $new_val; confess "Out of range!" unless $self-&gt;_is_in_range($new_val); } } </code></pre> <p>And I would present attributes on some <code>ThingWithScale</code> that were backed by a <code>Scale</code> object.</p> <pre><code>class ThingWithScale { has _attr =&gt; ( is =&gt; 'ro', isa =&gt; 'Scale', default =&gt; sub { shift-&gt;_make_attr() }, ); method _make_attr($class: $val?) { return Scale-&gt;new( min =&gt; 100, max =&gt; 1000, def =&gt; 200, (defined $val ? (val =&gt; $val) : ()), ) } # Convert `attr` argument to a `Scale` object before passing to real constructor. sub BUILDARGS { my ($class, %args) = @_; if (defined (my $attr = delete $args{attr})) { %args = ( %args, _attr =&gt; $class-&gt;_make_attr($attr) ); } return $class-&gt;SUPER::BUILDARGS(%args); } } my $thing = ThingWithScale-&gt;new(attr =&gt; 101); </code></pre> <p>And about the time I was writing that <code>BUILDARGS</code> method to automatically instantiate a Scale object from the simple constructor parameter, I would realize that what I really wanted to do was to invent a new attribute <a href="http://search.cpan.org/~ether/Moose-2.0900-TRIAL/lib/Moose/Manual/Attributes.pod#Attribute_traits_and_metaclasses" rel="nofollow">trait</a> to describe attributes that had minimum and maximum legal values.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload