I currently have a little crush in the builder pattern. This pattern and variations of it can solve common programming issues in a pretty straightforward way. I will give you an example of how you can use it in a validation context. A use case could be when you want to be able to perform different operations on the validation result. And you want a clean separation between the actual validation logic and the result of the validation. An advantage is that it is much less error prone e.g how to use the objects compared to letting a single class have all responsibility. Further it also makes it possible to have different “validation result objects” for the same validation logic, if needed.
public
class
PersonValidator {
private
static
final
int
MAX_SEQUENCE =
20
;
private
final
List
private
PersonValidator(
final
Validator validator) {
exceptions =
new
ArrayList
}
public
boolean
hasException() {
return
exceptions.isEmpty();
}
public
List
return
exceptions;
}
public
String getAllExceptionsFormatted() {
//
}
public
void
throwFirstExceptionIfAny()
throws
BaseException {
if
(!exceptions.isEmpty()) {
throw
exceptions.get(
0
);
}
}
public
static
class
Validator {
private
final
List
new
ArrayList
public
Validator isNullDoThrow(
final
Person person)
throws
BaseException {
if
(person ==
null
) {
throw
new
BaseException(
"Person must not be null"
);
}
return
this
;
}
public
Validator code(
final
String code) {
if
(StringUtils.isBlank(code)) {
exceptionsOccured.add(
new
ValidationException(
"Code must not be empty"
));
}
return
this
;
}
public
Validator sequence(
final
int
sequence) {
if
(sequence >= MAX_SEQUENCE) {
exceptionsOccured.add(
new
ValidationException(
"Sequence must be smaller than "
+ MAX_SEQUENCE));
}
return
this
;
}
@SuppressWarnings
(
"synthetic-access"
)
public
PersonValidator validate() {
return
new
PersonValidator(
this
);
}
}
}
Copyright © 2011 - All Rights Reserved - Softron.in
Template by Softron Technology