Monday, August 16, 2010

Unit tests catch documentation flaws.

I wanted to set a date and clear the time fields for it.

I quickly grabbed a calender object.

Calendar tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, 1);
tomorrow.clear();

The JavaDoc for .clear() states "Clears the values of all the time fields."  Which is awesome because I want the value to be tomorrow's date with no time.

However, the value of tomorrow at this point is 1/1/1970.  The writer of the documentation considered the date as part of the time fields.   

Instead I have to do this.
Calendar tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, 1);
tomorrow.set(Calendar.HOUR_OF_DAY, 0);
tomorrow.set(Calendar.MINUTE, 0);
tomorrow.set(Calendar.SECOND, 0);
tomorrow.set(Calendar.MILLISECOND, 0);


This will set the value to tomorrow without any time values.

Documentation is great, but be sure to test the results of the function yourself or you may end up with something other than what you expect.

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.