Reputation: 4035
In my POJO, i usually declare the fields like this
class SampleModel {
var field1: String? = null
var field2: Int? = null
<more fields here>
}
If I declare like this, I will need to check if the field is null or not.
But if like this:
class SampleModel {
var field1 = ""
var field2 = 0
<more fields here>
}
I can use it directly.
Does it matter on which declaration to use? Like in terms of memory, performance, or anything that a good practice to do?
Lets say I have 100 fields. Then I use Moshi or Gson for the deserializer.
Upvotes: 0
Views: 980
Reputation: 482
IMO, memory and performance should not be taken into account when you are choosing between these two approaches. It depends on how you want the class to behave. To have a default value (approach 2) or null (approach 1). It matters when you need to handle logic of this class.
Upvotes: 1
Reputation: 516
In the end even beyond performance considerations is quality of code. If the fields will never actually be null in your use cases then I would not use nullable types. You are forcing yourself to do extra work (albeit Kotlin makes it somewhat easier) to cater for a scenario that it seems like you're saying isn't possible?
On the other side; if a field in the serialized were to be missing in this scenario you may not immediately catch it because the field in the class has a default value. If you're confident in the data being provided though this shouldn't be a problem.
Upvotes: 1