[Pdx-pm] Too much validation

Tkil tkil at scrye.com
Thu Nov 20 18:09:58 CST 2003


>>>>> "Joe" == Joe Oppegaard <joe at oppegaard.net> writes:

Joe> So as a general rule of thumb, when should data validation be
Joe> done?  Catch it early or catch it when it actually matters? Or
Joe> both? (Ugh, duplicate code).

With object-oriented codde, I feel you should let the class decide
what is acceptable or not.  This lets me change what is considered
acceptable without editing all callers.

There are two ways I'd code this convention in Perl.  One requires a
bit of checking, but it is unobtrusive and straightforward:

| while ( my $raw_data = get_data() )
| {
|     # MyClass::new will return undef if $raw_data is invalid
|     my $obj = MyClass->new( $raw_data )
|       or next;
| 
|     # do stuff with $obj here
| }

The other way -- which I've adopted in most of my code of late -- is
to use "eval BLOCK" to catch "die" calls as exceptions:

| while ( my $raw_data = get_data() )
| {
|     eval
|     {
|         # MyClass::new will 'die' if $raw_data is invalid
|         my $obj = MyClass->new( $raw_data );
|
|         # do stuff with $obj here
|     };
| 
|     if ( $@ )
|     {
|         # complain
|     }
| }

This has the advantage of providing a description of what went wrong
in $@.  Further, it allows any method in MyClass to "die" if it can't
do what it promises to do.

There are existing modules that can be told to "die" if something goes
wrong, freeing you from checking the error return of every call.  A
fine example of this is DBI, with its RaiseError attribute.

t.



More information about the Pdx-pm-list mailing list