in reply to OO APIs and FP interfaces

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        

Replies are listed 'Best First'.
Re^2: OO APIs and FP interfaces (storage scope)
by Apero (Scribe) on Dec 04, 2015 at 15:55 UTC

    Great alternative, thanks! I see your point about additional work in the module to verify (and if necessary protect) correct operation, yet this seems to be a nice hybrid between giving a caller the ability to prepare a partially configured template and the flexibility to instantiate usable objects out of the templates. This is an excellent extension of the design options I originally proposed.

    This also has the benefit of being subclass-friendly, which choroba noted earlier as a flaw in package-scoped lexicals.