-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomerRegistrationValidator.java
More file actions
64 lines (55 loc) · 2.04 KB
/
CustomerRegistrationValidator.java
File metadata and controls
64 lines (55 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package combinatorpattern;
import java.time.LocalDate;
import java.time.Period;
import java.util.function.Function;
import static combinatorpattern.CustomerRegistrationValidator.ValidationResult;
public interface CustomerRegistrationValidator extends Function<Customer, ValidationResult> {
static CustomerRegistrationValidator isEmailValid() {
/*
* A very simple validation as the purpose is to under combinator pattern
*/
return customer -> customer.getEmail().contains("@")
? ValidationResult.SUCCESS
: ValidationResult.EMAIL_NOT_VALID;
}
static CustomerRegistrationValidator isPhoneNumberValid() {
/*
* A very simple validation as the purpose is to under combinator pattern
*/
return customer -> customer.getPhoneNumber().startsWith("+0")
? ValidationResult.SUCCESS
: ValidationResult.PHONE_NUMBER_NOT_VALID;
}
static CustomerRegistrationValidator isAnAdult() {
return customer -> Period.between(customer.getDateOfBirth(), LocalDate.now()).getYears() > 18
? ValidationResult.SUCCESS
: ValidationResult.IS_NOT_AN_ADULT;
}
/**
* Using combinator pattern to chain multiple validations together.
* @param other the other validation condition to check.
* @return The CustomerRegistrationValidator object with the current state of the result.
*/
default CustomerRegistrationValidator and(CustomerRegistrationValidator other) {
return customer -> {
/**
* This applies validation on customer object.
* apply() is a method of Function which this interface is extending.
*/
final ValidationResult result = this.apply(customer);
/**
* Ternary operator to check if further validations are necessary.
* Since the inner methods isAnAdult(), isEmailValid() and isPhoneNumberValid()
* also return CustomerRegistrationValidator, this combinator pattern works
* without problems.
*/
return result.equals(ValidationResult.SUCCESS) ? other.apply(customer) : result;
};
}
enum ValidationResult {
SUCCESS,
PHONE_NUMBER_NOT_VALID,
EMAIL_NOT_VALID,
IS_NOT_AN_ADULT
}
}