Question

I have a usecase where I am supposed to store entire payload from a third party API in addition to the DTO, say XYZDto, its translated to.

There are two ways to achieve that -

  1. Translate the payload into DTO as it is and when it comes to converting it into corresponding entity, I would do entity.apiPayload = convertToJson(dto)

  2. Another way is to have to have a payload field in dto itself and write my own mapper which does the following.

    a. Perform the usual payload to DTO conversion

    b. Store the payload in DTO dto.apiPayload = payload This way payload will already be ready while converting to entity and we will just do entity.apiPayload = dto.apiPayload

As I understand, advantage of Option 2 is there will not be unnecessary translation of dto back to payload at runtime.

I want to understand if there is a design pattern or rule that I am breaking here. Am I missing any trade-offs between DTO strictly having the same structure as its payload vs. having a different structure?

Was it helpful?

Solution

Let me reword your question in a more general fashion:

  • there are two different representations of the same block of data (here a DTO representation and a JSON representation)

  • there are different processing steps, some needing the first representation, others which need the second

Should one

  1. use only one representation at a time, and convert to the other on-demand, or

  2. keep both representations side-by-side, so there is no later conversion required?

Option 1 is definitely required if the intermediate processing steps can change the content of the data, otherwise the result will get wrong. For example, when in the steps between "converting the payload into DTO" and "converting it back to a JSON string" the DTO content changes, the original payload would not match the DTO content any more.

Option 2, however,

  • may be faster (note this if often negligible)

  • may need twice the memory (note this if often also negligible)

  • might be simpler when it saves the need to write conversion code in one direction (in the example, implementing convertToJson may not be needed any more - but note this benefit vanishes if the backconversion code is still required for other purposes)

  • might be required if one wants the 100% identical, original source representation of the data, including meta data, comments, whitespaces and so on, and the "back conversion" function (like convertToJson) does not easily guarantee this accuracy

  • may introduce errors if one of the two representations is not kept immutable (as I already wrote above)

So this is a tradeoff, analyse your requirements in contrast to the points I mentioned above, then pick your choice.

Licensed under: CC-BY-SA with attribution
scroll top