Search code examples
javadto

Which is better adding new fields to existing DTO class or new DTO class?


This may be a general java question

DTO1

  1. attribute1
  2. attribute2
  3. attribute3

DTO2

  1. attribute1
  2. attribute2
  3. attribute3
  4. attribute4
  5. attribute5
  6. attribute6
  7. attribute7
  8. attribute8
  9. attribute9
  10. attribute10
  11. attribute11
  12. attribute12

I'll be showing some list of values in a gxt grid on my screen. Those values are nothing else but a list of DTO1 class in which I have 3 strings which I'll be getting from a service call. Now I need to show 12 different fields in a similar fashion but based on a condition (I won't be showing DTO1 this time around).

Is it better (performance wise) to create a new DTO2 class with those 12 fields or add these 12 fields to the existing DTO1 class so that I don't have to create a new DTO2 class anymore.

Case 1. Added extra fields to the existing DTO class
Wouldn't there be extra space each time I'm using the DTO class for only 3 attributes instead of the newly added 12 attributes?

Case 2. New DTO2 class created
Can the extra space created be compensated by adding those 12 fields to the DTO1 as in case 1?

Throw some light on which approach improves the performance?


Solution

  • If your DTO2 has 3 of its 12 attributes the same type as DTO1, you should definitely use inheritance:

    class DTO1{
    
        private String attribute1;
        private String attribute2;
        private String attribute3;
    
        //getters and setters
    }
    
    class DTO2 extends DTO1{
    
         private String attribute4;
        //other attributes
    }
    

    and use DTO2 wherever you neeed exactly all the 12 attributes, and DTO1 when you need only 3 attributes.

    If your DTO2 doesn't have at least 3 attributes the same type as DTO1, you should create a new separate DTO2 class. There's no purpose in adding all the 12 attributes to DTO1 and use only 3 of them, because the JVM will allocate memory for all 12 of them them when you create an instance of your DTO1, even though you do not initialize those other 9( each reference would occupy 4/8 bytes - depending on the machine JVM is running).

    Of course, a few bytes more are insignificant, unless you deal with millions of DTOs. But if we consider the design, and the posibillity that in the future you will need multiple kinds of DTOs, you should not rely only on one type of DTO to do your job.

    As for the extra space added by DTO2 fields, there is no way around. If you need 12 attributes, you have to allocate memory for them, so there's nothing wrong here.