1

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

1
  • 4
    Hey, It would be good if you could add some mock examples to demonstrate...
    – Tom Taylor
    Commented Nov 30, 2018 at 5:19

1 Answer 1

3

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.

2
  • 1
    Agreed. Interface classes are better off self-representing themselves and not dependent on other classes, even if it means repeating fields.
    – Neil
    Commented Nov 30, 2018 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
    Commented Dec 3, 2018 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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