Skip to content

Instantly share code, notes, and snippets.

@mariogarcia
Created August 25, 2014 12:22
Show Gist options
  • Save mariogarcia/558acc31cc25e4445667 to your computer and use it in GitHub Desktop.
Save mariogarcia/558acc31cc25e4445667 to your computer and use it in GitHub Desktop.
Thinking about business validation + functional style
interface HasUser {
User getUser()
}
interface HasBank {
Bank getBank()
}
interface Validator<T> {
Boolean validate(T validateable)
}
class User {
String name
}
class Bank {
Long id
}
class AddBankToUserEvent implements HasUser, HasBank {
User user
Bank bank
}
class BankValidator {
Validator<HasBank> isValid() {
return { HasBank hasBank ->
hasBank.bank.id == 11
} as Validator
}
}
class UserValidatorService {
Validator<HasUser> isNotRisky() {
return { HasUser validatable ->
validatable.user.name != "Risky"
} as Validator
}
}
class Validating<T> {
T validatable
Validating<T> validate(T o) {
validatable = o
return this
}
Closure<Boolean> validationResult = { v -> v.validate(validatable) }
Boolean withValidators(Validator<T>... validators) {
return validators.collect(validationResult).every()
}
}
def userValidator = new UserValidatorService()
def bankValidator = new BankValidator()
def event =
new AddBankToUserEvent(
user:new User(name: 'lala'),
bank: new Bank(id:11)
)
def passingValidation = new Validating<AddBankToUserEvent>()
.validate(event)
.withValidators(
userValidator.isNotRisky(),
bankValidator.isValid()
)
println "Passing validation: $passingValidation"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment