Hello dear esteemed monks,

I have a class that is read-only. It does have parameters, but for the most cases a default instance would fit. So I'd like to avoid unneeded initialization and just return $ONE_AND_TRUE_INSTANCE if such exists and no parameters are given to new().

Here's how I would've done this outside Moo/Moose:

my $ONE_TRUE_INSTANCE = __PACKAGE__->new; sub new { my ($class, %args) = @_; return $ONE_TRUE_INSTANCE if ($ONE_TRUE_INSTANCE and $class eq __PACKAGE__ and !%args); # normal constructor here ... };

Can the same be achieved with Moo? How can my example code be improved? Maybe there's a proper architectural solution and/or pattern for this?

Thank you,

UPDATE: actually I can do this with Moo, so the question remains - what can be fixed in architecture to avoid the need for "defaulton":

package Defaulton; use Moo; has foo => is => ro => default => sub { 42 }; my $INST = __PACKAGE__->new; around new => sub { my ($orig, $class, @args) = @_; return $INST if $INST and $class eq __PACKAGE__ and !@args; return $class->$orig(@args); }; 1;

In reply to Caching a default instance to avoid initializing it every time (with Moo) by Dallaylaen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.