Calendar

Of Coding Standards and Good Code Pt 2

This is part two of coding standards and good code quick-bits. You can read part one here.

Give Me A Date

Today we are going to talk about dates and how you should not date. Out in the wild, in production code in a Java application, I have run into this gem [WARNING The following code will make your brain hurt]:

public static String parseDate(final String paramDateString){
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm");
	Date date = null;
	
	try {
		date = sdf.parse(paramDateString);
		sdf.setTimeZone(TimeZone.getDefault());
		return sdf.format(date);
		
	} catch(ParseException exception){
		exception.printStackTrace;
	}
	return null;
}

...

String dateTime = parseDate(someDateValue);
String date = dateTime.split(" ")[0];
String time = dateTime.split(" ")[1];

String timeHH = dateTime.split(":")[0];
String timeMM = dateTime.split(":")[1];

Let us ignore that our parseDate method is just fixing the time zone, the high possibility of a null pointer exception for incorrect date formats, extracting date parts as Strings and talk about the unnecessary abstraction. Look, every programing language has some sort of Date object as part of its standard library or a third party library you can add to your project. If the language you are using now does not, then change your tech stack.

If you ever find yourself handling dates or parts of a date as Strings or defining your own date object, you have made a series of grave mistakes and are now writing absolute garbage.

See you in part three!