Re: Design Pattern for Validation

[email protected] (Karen Etheridge)
Newsgroups perl.moose
Message-ID <[email protected]>
On Tue, Oct 11, 2011 at 04:30:25PM +0200, Peter Gordon wrote:
> I am trying to find a decent design pattern for Moose validation of
> user input. All the Moose examples I have found either assume that 
> the data is correct or else dies.

...
> From an OOP perspective, it seems to me that the validation performed
> by the subtype should be part of the class and not something that is
> just floating around.

Agreed - since we already have the class's constraints right there in the
class definition, we can just use existing moose code to perform data
validation in an object instance.

>                      There is also no reasonable way to trap the
> error, and report back to the user that there was an error. And I am
> not a fan of try/catch.

Check out MooseX::Constructor::AllErrors - this is exactly what it was
designed for.  You still need to use a try block, but this is not a code
smell on its own -- and you will get *all* type violation errors back (as
well as other errors like missing attributes that are required=>1, etc), in
a tidy object that you can query to get the nature of the error(s) that
occured.

Example (uses TryCatch):

my $obj;
try
{
    $obj = $class->new(%args);
}
catch ($exception)
{
    my $meta = Class::MOP::class_of($exception);
    my $message = blessed $meta && $meta->isa('Moose::Meta::Class')
        ? join('; ', map { $_->message } $exception->errors)
        : $exception;

    log_error("failed to construct a $class: ", $message);
}


PS. As an aside, I gather from irc #moose that a few folks have been
looking into other nicely-formed exception classes for Moose - if the same
API could be used as in MX::C::AE, then the above code block will work in
other situations as well as at construction time.


-- 
     "Sometimes there is a silver bullet for boosting software engineering
     productivity. But you need to shoot the right person." - Craig Andera
            .             .            .            .             .
Karen Etheridge, [email protected]       GCS C+++$ USL+++$ P+++$ w--- M++
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.