why not a factory method to return null when neces...
# android
m
why not a factory method to return null when necessary instead?
j
menegatti: Can you elaborate on what you mean by that?
m
well, have a companion object with a method that takes the json and returns null in case it's not valid
I don't think data classes have a really good way of achieving what you're trying to do by themselves
j
To extend on your point for a companion object, why not a function instead that massages the json and return null if not valid?
If not a data class, then what?
m
I mean, you would still use a data class
but a method will work on the instance itself and validating the json should be a step before, don't you agree?
meaning... you verify whether or not it is a valid json and then decide on whether you should create an instance of the data class or not
so it seems like a case where I would use a static (companion object) factory method that takes a json and returns your class in case the json is valid, null otherwise
j
I see where you’re getting at now. Interesting, never thought of that. Will give it a shot.
Have you personally never encountered such cases before though?
OR, alternatively we could make the constructors throw an exception, no?
m
yes, definitely
j
Noted, thanks Edson!
m
also you could let the json do its magic
and after parsing you just filter out the instances that don't pass a certain validation, does that make sense?
j
Haha, I thought of that too actually
m
if you wanna go very clean about it, have an interface like
Validator
with a method
validate
or something, and filter out by the return of validate, but then it's a matter of taste
k
constructors throwing exceptions are bad style. I support the suggestion for a factory method.
Kotlin's nullability language features lend themselves very well for early returns:
Copy code
fun create(json: JosnObject): MyClass? {
    val id = json.opt("id") ?: return null
    ...
    return MyClass(id, foo, bar, ...)
}