Skip to content

Instantly share code, notes, and snippets.

@sankemax
Last active April 17, 2020 18:49
Show Gist options
  • Save sankemax/6825385264b784d77122baee68a6a9ff to your computer and use it in GitHub Desktop.
Save sankemax/6825385264b784d77122baee68a6a9ff to your computer and use it in GitHub Desktop.
An example of a simple validator pattern
import java.util.*;
data class Error(val reason: String, val path: String)
class Address(
val municipality: String,
val neighbourhood: String
)
abstract class Validator<T>(val toValidate: T) {
abstract fun validate(): List<Error?>
}
class AddressValidator(toValidate: Address) : Validator<Address>(toValidate) {
override fun validate(): List<Error> {
return listOf(
this::isMunicipalityValid,
this::isNeighbourhoodValid
)
.asSequence()
.map { it(toValidate) }
.filter { it.isPresent() }
.map { it.get() }
.toList()
}
fun isMunicipalityValid(address: Address): Optional<Error> =
if (address.municipality.isBlank()) Optional.of(Error("municipality is blank", "address.municipality"))
else Optional.empty()
fun isNeighbourhoodValid(address: Address): Optional<Error> =
if (address.neighbourhood.isBlank()) Optional.of(Error("neighbourhood is blank", "address.neighbourhood"))
else Optional.empty()
}
fun main() {
var address = Address(
municipality = "municipality",
neighbourhood = "neighbourhood"
)
println(AddressValidator(address).validate())
var address2 = Address(
municipality = "",
neighbourhood = "neighbourhood"
)
println(AddressValidator(address2).validate())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment