When I build mobile apps (but platform doesn’t matter) I run into trouble with model classes.
For example, let’s say I will have model class called User
with properties id
, name
and age
. I fetch users from remote API, parse JSON into instance of this model class and these properties are being displayed somewhere in list (note that other properties are not present in JSON response). So far, so good.
But at some point, in another part of the application I will also need to obtain other User
‘s properties, such as address
, email
, etc. I’m having a hard time deciding how to proceed and that’s also my question. Should I now create a new model class? Inherit from User
class? Or make all fields nullable
?
Basically what I do everytime is that I set every properties as nullable
and populate only what is needed. Is this good approach? I can’t shake the feeling that there is a better way to do it.
2
Answers
Alright, So different parts of your app need different properties of User Object!
It depend on, how do you obtain that User from API, do you get that User from a single endpoint using a single call, or it’s distributed (obtain basic data from endpoint or API and other data is obtained from another endpoint or API).
So, if you obtain that user from a single endpoint, you should accept all of its properties that are likely will be used in your app.
If not single endpoint or API, it’s complicated right now, but you can solve it by extending the existent user and make a sub class from it that contain that additional data (got it!)
for example:
BTW, making a lot of properties
nullable
is an overhead because working with nullable require a lot of validation (null-safety).If you additional JSON value are options, i.e. they may be present or not for each individual item, then making the fields
nullable
in your model class is reasonable. Otherwise you’ll end up with a combinatorial explosion of classes with different sets of fields.As an advanced topic, you may consider wrapping optional fields in instances of
Optional<T>
. This gives you null-safety and optional values at the same time.You should also consider making you model classes immutable, using the freezed package