Cloning Date
by Remy Porter
in CodeSOD
on 2017-03-02
We get a lot of bad date code samples. Since we all learned to read a calendar in elementary school, everyone assumes they actually understand how dates work, and then tries to codify that knowledge in code. Bad date code is like entry level awfulness, and it takes a lot to surprise me when I see bad date handling code. Mike R knows how to do it, though. He found this code buried in a 30+ file commit, with the helpful commit message, “asdf;”:
public class DateUtil {
private DateUtil() {
}
public static Date setDate(Date date){
if (date == null) {
return null;
}
return new Date(date.getTime());
}
public static Date getDate(Date date){
if (date == null) {
return null;
}
return new Date(date.getTime());
}
}
public class DateUtilUnitTest {
@Test
public void testSetDate() throws Exception {
Date date = new Date();
Date result = DateUtil.setDate(date);
assertThat(date,is(result));
}
@Test
public void testSetsNullDate() throws Exception {
Date date = null;
Date result = DateUtil.setDate(date);
assertThat(date,is(result));
}
@Test
public void testGetDate() throws Exception {
Date date = new Date();
Date result = DateUtil.getDate(date);
assertThat(date,is(result));
}
@Test
public void testGetsNullDate() throws Exception {
Date date = null;
Date result = DateUtil.getDate(date);
assertThat(date,is(result));
}
}