Friday, 11 July 2008

I wouldn't have thought of that...

One really good thing about working on older code written by someone else (or many other people) is that you see all kinds of new things. Some are tricks, some are hacks, some are just... "different". I find myself going over code sometimes, trying to figure it out, and coming to a realization of what it does.

The really interesting ones are the ones where I say to myself "I would have never thought of that!". That can be a good thing, a bad thing, or just different. The one that I came across the other day was a method for deep cloning an object using serialization. The method serialized the object into byte buffer, and then wrote it right back into a new object.

I usually hate clone methods to start with, using a copy constructor instead in the rare cases I need to make a copy of something. One disadvantage I've found doing this is that you have to be very careful that you clone all the attributes of that class properly. That way you don't get 2 objects pointing to the same list for example.

One advantage of the serialization clone method is that you're not going to run into this problem and it's somewhat "future proof". Interesting. Hugely expensive and tricky, but interesting.

No comments:

Post a Comment