Java Reference
In-Depth Information
Tim Says. . .
Use the Minimum Number of Validation Methods Neces-
sary to Get the Job Done
Stripes will happily invoke any number of validation methods in
a single Action Bean. As Freddy has shown, there are mech-
anisms for coordinating the ordering of the validation meth-
ods and whether they should be executed when errors already
exist. So, you might be thinking that the best thing to do is to
have a method for each custom validation you want to write
and then let Stripes execute them in order. In my experience,
though, it's often easier to write and maintain action beans
where custom validations are grouped into as few methods as
possible—often only one.
The main reason is that, for Java developers, it's always going
to be more natural to understand the flow of code in a single
method than to understand the rules used by a framework for
ordering the execution of a set of methods. For example, it is
fairly obvious when the following pseudo-code executes and
what it does:
@ValidationMethod
public void validateUniqueFields(ValidationErrors errors) {
if (username != null && userDao.exists(username)) // add error
if (email != null && userDao.emailExists(email)) // add error
if (username != null && password != null
&& password.indexOf(userName) >= 0)) // add error
}
The preceding code is reasonably compact, and anyone famil-
iar with Java will be able to tell what it does: all three valida-
tions are run, in order, regardless of whether preceding checks
in the same method failed. By contrast, the following code
requires much deeper knowledge of Stripes to determine the
same information:
@ValidationMethod public void validateUniqueUsername() {...}
@ValidationMethod public void validateUniqueEmail() {...}
@ValidationMethod public void validateUsernameNotInPassword() {...}
The previous code, with method bodies filled out, will also be
much less compact. The one time it does make sense to start
splitting custom validations into multiple methods is when you
have multiple events that require either overlapping or com-
pletely different validations. In these cases, you will find it best
to split the validations into methods that can be shared across
events without duplicating the code.
 
 
Search WWH ::




Custom Search