http://www.perlmonks.org?node_id=862817

bichonfrise74 has asked for the wisdom of the Perl Monks concerning the following question:

My goal is to able to switch from a sandbox user to production user. So, I have the code below. I am wondering if this is a good approach or if there is a better way.
package Testme; use warnings; use strict; use Exporter; sub New { my ($class) = @_; my $self = { sandbox => '0', }; if ($self->{sandbox} == 1) { $self->{user} = 'sandbox_user'; $self->{password} = 'sandbox_password'; } else { $self->{user} = 'production_user'; $self->{password} = 'production_password'; } bless( $self, $class ); return $self; }
1;

Replies are listed 'Best First'.
Re: Configuration Question
by moritz (Cardinal) on Sep 30, 2010 at 18:16 UTC
    I typically have such credentials in a config file, and have one config file for the sandbox and one for the production system.

    Then I can either switch by host (ie one config file per host), or set a symlink, or have an environment variable or command line switch to chose one.

    A config file also has the advantage that I don't need to put sensitive data under version control.

    Perl 6 - links to (nearly) everything that is Perl 6.
Re: Configuration Question
by ikegami (Patriarch) on Sep 30, 2010 at 18:43 UTC

    The constructor probably shouldn't access the config file itself. Why not pass the user/pass to the constructor (which should really be called new)?

      Why should the constructor be called new and not New?

      Is it preferred to have methods in lower case? Or is it because 'new' is a constructor and so the convention is to put it in lower case?

        Perl Best Practices describes some excellent ideas (and also contains some crud, so don't believe everything, just because it's in print ).

        • Use lower case for subroutines, methods, variables and labelled arguments.
        • Use Mixed-Case for package and class names.
        • User UPPERCASE for constants.

        But as far as your example is concerned, you hardcode sandbox to 0, then test whether it's 1, which of course it isn't. Maybe some user input would be good. It would be better to find a means to connect which doesn't involve passwords at all. Or if you need one, have it supplied on the command line?

        As Occam said: Entia non sunt multiplicanda praeter necessitatem.

        Is it preferred to have methods in lower case?

        Most do, yes. More specifically, this is the first time I've ever see New. It's jarring, to say the least.

Re: Configuration Question
by hesco (Deacon) on Oct 01, 2010 at 01:41 UTC
    Moritz offers sage advice, to which I would add: check out Config::Simple, or some other related module for parsing a config file and returning an accessible configuration hash. -- Hugh

    if( $lal && $lol ) { $life++; }
    if( $insurance->rationing() ) { $people->die(); }