0

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.

Community
  • 1
  • 1
iadcialim24
  • 3,817
  • 5
  • 21
  • 32
  • For perf, values like the empty string are interned and don't cost anything. For code, it depends on what you are trying to do and if you really want default values. You can make data classes with constructors that take non-nullable types and use Moshi's KotlinJsonAdapter to require those JSON fields. – Eric Cochran Oct 27 '17 at 05:28

2 Answers2

1

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.

dillius
  • 506
  • 4
  • 12
  • Which part of my question says something that is not possible? – iadcialim24 Oct 26 '17 at 10:38
  • If it were possible I would not see any reason to consider the 2nd option at all? If null is possible then you have to have nullable types, and you gain no advantage by putting default values on nullable types. – dillius Oct 26 '17 at 10:47
1

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.

CrazyApple
  • 472
  • 2
  • 9