Can a DTO have basic object-level operations like Clone?

I understand that a strict definition of DTO should serve as a container for data transfer, it should not have any behavior. However, I came across a situation with the need to clone DTO, two options: 1. create the Clone method (ICloneable?) In DTO 2. create a general utility class for DTO cloning

I am currently using option # 2. However, I think No. 1 is acceptable if there is no logic in the DTO. I would like one of you to face a similar situation with DTO, which required basic operations such as Clone, ToString, especially DTO, which had inheritance. Thanks.

+6
source share
2 answers

If it is a DTO, it should be designed for serialization - in this case, your best option is to serialize it using any process that it has developed and take the clone from there. It is quite rare that this will be a performance issue.

+3
source

A clone is an operation that is not really needed. However, if you really need to clone objects, they are quite acceptable for its implementation directly on the object. This will allow you to access MemberwiseClone 's protected function in relation to ICloneable

Cloning is often implemented using the MemberwiseClone element. See Unable to access protected member object .MemberwiseClone () ' .

If you need deep cloning of a graph, check out BinaryFormatter to clone your object. Or look at the model change to not expect cloning.

+2
source

Source: https://habr.com/ru/post/896435/


All Articles