I have a DAO that brings data from a web service, that data comes in a string, in the likes of:
*NAME|John Doe *DATEOFBIRTH|1978-23-01*ID|anID123 (...)
I have a DTO that I wanna fill up with the parsed data (the DTO has fields in the like of name, birthdate, id…)
So, my question is, what is the best practice:
- Parsing the string in the DAO to fill up the DTO
- Passing the data string to the DTO and the DTO itself parse the string and fill itself up
- Do the parsing in an utility class that would receive the string and return the fill up DTO
DAO: Data Access Object
DTO: Data Transfer Object
Note: I kept this language agnostic so it could be useful to anyone using object oriented languages, but, in my particular case, I’m using Java.
0
Typically an unmarshalling construct can be used.
The job of the unmarshaller would be simply to translate from the string to your domain specific DTO. Your DAO or DTO will not need to change if the transmission format changes. Additionally, the unmarshalling strategy can be mocked out for unit tests (and tested separately). Depending on your enterprise architecture pattern, you can invoke the unmarshaller anywhere (in the DAO, the DTO, using AOP, …).
Many widely used software packages use the marshalling/unmarshalling concept including Spring, JAXB, and the AWS Java SDK. I suggest that you take a look at these libraries to get some ideas as to how you can implement and fit into your design (you may find a ready made solution that fits your needs).
2
The DTO should be responsible for filling up its own fields from the parsing result, because the fields are specific to the DTO.
The parsing itself can take place elsewhere, but Java has a Split()
function, so your DTO already knows how to parse it. So just hang a Parse(string)
function onto your DTO.
2