in reply to Re: confusing constructor code
in thread confusing constructor code

You're right except that you need to check the number of parameters to avoid this warning:
Odd number of elements in hash assignment
I usually use it like this:
my %args = @_ % 2 ? () : (@_);

Replies are listed 'Best First'.
Re^3: confusing constructor code
by Corion (Patriarch) on Jul 01, 2008 at 07:52 UTC

    That warning is there for a reason and your code is different from my code.

    Your code assumes that the class name has been shifted out of @_ already while my code assumes it's still in @_. I would like to keep the warning just in case somebody (that is, I myself) calls the constructor with the wrong number of arguments. Having the code silently swallow all arguments would be far worse than having a warning telling me what's wrong.

      Of course you need to do my $class = shift;. I didn't see a reason to write the full code. You have to die() instead of warn() if explicit check is needed. Ignoring bogus parameters is a way too.
Re^3: confusing constructor code
by dragonchild (Archbishop) on Jul 01, 2008 at 12:55 UTC
    Corion is right that this code isn't sufficient. The goal isn't to avoid warnings; it's the avoid the situations that bring about warnings. Plus, your method will, in most cases, cause the object to be useless. Returning useless things is worse than dying loudly.

    In this case, the situation is where the wrong arguments are coming in. Thus, we should probably look at more situations than just the wrong number of arguments. So, we probably want to be looking at the argument names, too. And, maybe even look at validating the values. Maybe we want to allow foo and -foo. In other words, stop hand-rolling and just use Params::Validate.


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?