The problem with your approach is that you are storing the "config" in a global scope which means that users of this module in one part of your application can stomp on users of this module in some other part of your application.

A much better approach is to let the user of the module decide where to store any particular "config".

my $conf = Ex::mod->conf(user=>'Alice'); my $a = $conf->new();

And that is even trivial to achieve by allowing creation of incomplete objects.

sub new { my( $conf, %opts ) = @_; my $class = ref($conf) || $conf; # subclass boilerplate. $conf = {} if ! ref $conf; my $self = { user => $opts{user} // $conf->{user} // '', }; return bless $self, $class; }

Depending on your use case, you might have separate c'tors for partial objects that can only serve as "config" vs. fully-initialized objects. For example, a useful object might require a connection to a service, a step that only happens when new() is called but you can pre-set default values in an object by calling the conf() class method.

In your simple example, you can just use the new() method to also be your "conf" method.

One minor down side is that you'll likely need to have methods that do work protect themselves from being called on incomplete objects. But that is often quite simple and obvious:

sub send_request { my( $self, ... ) = @_; croak "Can't send_request via incomplete object\n" if ! $self->{socket};

- tye        


In reply to Re: OO APIs and FP interfaces (storage scope) by tye
in thread OO APIs and FP interfaces by Apero

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.