Is there a pattern that helps tell the user at runtime all the reasons their object (or payload) is invalid?
I have an object Foo that, to be valid, needs params a and b to not be null. Unfortunately the parent method that creates it does not guarantee those params will not be null.
I can solve for this with something like the below, but it feels messy and like it won't scale nicely. Is there a better pattern for this?
fun parentMethod(a: String?, b: String?){
// do stuff
try {
val foo = Foo(a, b)
} catch (e: Exception) {
LOG.info("Exception when creating a Foo", e.message) // contain *all* error messages
}
}
class Foo(a: String?, b: String?){
init {
val errors = []
if(a == null){ // How do I tame this?
errors.push("a cannot be null)
}
if(b == null){
errors.push("b cannot be null")
}
if (!errors.isEmpty()) {
throw InvalidFooException(errors.toString())
}
}
}
Aucun commentaire:
Enregistrer un commentaire