I need to send a json response. I use the jackson library to convert the class to json. I have a core java class to which I need to add some more fields to create my json response. I came with two ideas.

  1. To extend the core java class.
  2. To have an another class with the core class object as constructor.

Concerns over two methods are:

  1. I have a core layer which returns core java object from database. I need to call a method to return my extended class object. In core layer, I have to create instance of the extended class and return
  2. I can easily achieve json response with this but for every object, there will be a wrapper kind of object created.

Kindly guide me to have a design pattern for this

  • 4
    Hey, It would be good if you could add some mock examples to demonstrate... – rm -rf star Nov 30 at 5:19
up vote 3 down vote accepted

I used to struggle with this issue a lot. But luckily, it has a well defined answer: go with your second option, and just go ahead and make another class.

This seems less obvious because you are afraid of repeating yourself; however, let me assure you, having a separate DTO is not repeating code. This is because these two classes have completely different purposes and occupy different domains. They may seem similar, but these similarities are coincidental, not causal.

What if the client consuming the JSON needs one of the fields removed to save on performance because it is too large? You can't remove that field from the core object, so you'd be in a very tricky situation if you used the inheritance option.

Don't be afraid to add more classes where you need to; it makes things simpler in end and actually reduces the total amount of code.

  • 1
    Agreed. Interface classes are better off self-representing themselves and not dependent on other classes, even if it means repeating fields. – Neil Nov 30 at 15:36
  • 1
    Thanks for you answer. Later I found that my question is similar to Composition vs Interface. As you suggested, many preferred Composition (Class has a) relationships. – ksv Dec 3 at 10:44

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.