Last active
April 17, 2020 18:49
-
-
Save sankemax/6825385264b784d77122baee68a6a9ff to your computer and use it in GitHub Desktop.
An example of a simple validator pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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