0

I have an object of type Record which implements Serializable. In my task, I have to split it into two objects of the same type, where one has all original fields except for one field, and the other only the field excluded at the previous step. Here is what I did:

Record firstPart = SerializationUtils.clone(record);
Record secondPart = new Record();
firstPart.setUid(null);
secondPart.setUid(record.getUid());

Now, I was told that I shouldn't have cloned record. Perhaps they mean it's too expensive if the record is big enough. I tried to figure out how to avoid cloning, but can't get it. What could be the solution?

Danny
  • 528
  • 1
  • 4
  • 27
  • 1
    Why not create and use a copy constructor? – Hovercraft Full Of Eels Jun 13 '22 at 13:19
  • This is somewhere deep in a big legacy app. I am not expected to change much in those classes that are not of my own. – Danny Jun 13 '22 at 13:21
  • 1
    `#clone` is protected, and is not typically intended to be called outside of the controlling class (`Record`). There's a [litany of reasons](https://stackoverflow.com/questions/26578517/should-i-use-clone-method-in-java) to avoid its usage, but that doesn't mean it isn't always possible. A "copy constructor" in this case would be more explicit and clear to someone reading the code. If it's already `Cloneable` then go wild, but otherwise definitely don't introduce `Cloneable` if it isn't there. For context, `Object#clone` does _nothing_ if the object doesn't implement `Cloneable`. – Rogue Jun 13 '22 at 13:22
  • Thank you. We are not talking about Object.clone() here, right? It was about SerializationUtils.clone(). – Danny Jun 13 '22 at 13:27
  • Regarding my comment, I took the liberty to assume `SerializationUtils#clone` would call `Object#clone`. – Rogue Jun 13 '22 at 13:33
  • It's really not clear.It looks like the SerializationUtil is going to serialize and de-serialize the object. So it doesn't really fall into the normal 'clone' category. There could be numerous reasons why this is bad. You'd have to ask why they told you not to use it. – matt Jun 13 '22 at 14:16

0 Answers0