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?

6
  • 1
    Why not create and use a copy constructor? Commented Jun 13, 2022 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. Commented Jun 13, 2022 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 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. Commented Jun 13, 2022 at 13:22
  • Thank you. We are not talking about Object.clone() here, right? It was about SerializationUtils.clone(). Commented Jun 13, 2022 at 13:27
  • Regarding my comment, I took the liberty to assume SerializationUtils#clone would call Object#clone. Commented Jun 13, 2022 at 13:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.