Validation and defensive programming
You may have noticed that our code is somewhat simple in respect to validation. This is because we are using JSR-303/349. No layer trusts its client. Instead of having lots of if
statements to check for null parameters and validate the values of the parameters are correct according to our rule, we instead use annotations. In the preceding code fragments, the parameters to our methods are annotated with @NotNull
and @Valid
, which instructs Spring Boot to validate the parameters. @NotNull
means the parameter must not be null, and @Valid
means the object passed in must be valid according to the annotations specified against its member variables.
Our Password
class, for example, has an instance variable annotated with @NotEmpty
and @StrongPassword
. @NotEmpty
means the variable cannot be null or blanks, and @StrongPassword
is a custom annotation that enforces the rules for a strong password:
@NotEmpty @StrongPassword private String password;...