Friday, August 06, 2010

Don't clone an object when you don't need to.

I was working with a piece of code today and I stumbled across a method that had this chunk of code in it.


Iterator iter = results.iterator();
while(iter.hasNext())
{
MyRecords existingTO = (MyRecords)iter.next();
MyRecords newTO = new MyRecords();
newTO.setDateLoaded(existingTO.getDateLoaded());
newTO.setFileExtension(existingTO.getFileExtension());
newTO.setFilenetID(existingTO.getFilenetID());
newTO.setFilenetName(existingTO.getFilenetName());
newTO.setOriginalName(existingTO.getOriginalName());
newTO.setDescription(existingTO.getDescription());

newTO.setFileSize(getFileSize(existingTO.getFilenetName()));
result.add(newTO);
}


This code gets data from a data access layer, then makes a clone of each item adding it to a new list while setting the FileSize.   However, there is no need to create a clone of the object.  The only thing required is to get the file size and set it.   A much cleaner smaller method is.



Iterator iter = results.iterator();
while(iter.hasNext())
{
MyRecords existingTO = (MyRecords)iter.next();
existingTO.setFileSize(getFileSize(existingTO.getFilenetName()));
}


This does the exact same thing without creating all the extra objects to store in memory.

No comments: