07/17/2020, 8:07 PM
Kotlin nullability/android question. If your backend dev is sending a payload with a String which is never expected to be null, should we be making that string nullable in our response object on the client-side, on the off-chance that the backend sends a null string? Should every response object and its fields be nullable to avoid NPEs?

Casey Brooks

07/17/2020, 8:37 PM
My team has a brittle API which sometimes sends default error objects instead of proper error status codes (I know, it’s gross), and for that reason we have to assume any given property coming from an API could be null. We have separate models for the API and UI, and do manual mapping to get the null-safety we want in our UI, and leave the messy nullable models just in the API. But it also isolates the majority of our app from changes to the API, and I think is a good practice to use in general

João Gonçalves

07/17/2020, 8:40 PM
you could introduce a validation/transformation layer between http response and your local data model
👆 3


07/18/2020, 4:21 AM
Pretty much exactly what was said above me are the things I'd recommend. You just want to make sure if you introduce some type of mapper between API response -> your frontend/UI model, that your UI handles bad data gracefully. So in the case that a field that shouldn't be null comes down as null, you create either a default value when mapping to your UI model or have a different model representing the default state altogether, for a better user experience.


07/18/2020, 7:55 PM
Making everything nullable in your API models is unnecessary. Even if you do, your deserialization won't crash, sure, but you still have to handle the case of unexpected
. Some fields just must not ever be
, like the
field of a domain entity. Your validator/mapper will have to cope with it. If your backend sends you a list of entities, some of which have
ID by mistake (remember, entity ID must never be null), what do you do then? Do you just skip over them? - inconsistent data. Do you block the application? - unusable app. Do you delete cache and redirect user back to login? - user stuck in a login loop. Making every field nullable in your API model just moves the problem elsewhere. Some fields can be safely made not nullable at the API model level, like the aforementioned entity ID. And also many other fields, depending on your domain. Presumably a field named
could never be null. How could your user create an account without
, right? So
val username: String
is pretty safe.