Wednesday, April 25, 2012

Simplifying Time Conversion

Recently I refactored some old code with a friend. The functions we were writing allowed us to practice both TDD and DRY. We demonstrated the code to our class yesterday and immediately, many constructive comments were offered. It immediately made me feel that I was back to Level I. However, I would like to share what I learned about the Java String.format() function.

Here is the code my pair programming partner and I came up with for this self-explanatory function:

public static String monthDayYearToString(int month, int day, int year) {
  String monthString = Integer.toString(month);
  String dayString = Integer.toString(day);
  String yearString = Integer.toString(year);
  
  if (month < 10) {
    monthString = "0" + monthString;
  }
    
  if (day < 10) {
    dayString = "0" + dayString;
  }
    
  String formattedDate = monthString + "-" + dayString + "-" + yearString;
  return formattedDate;
}

Here's the refactored code:

public static String monthDayYearToString(int month, int day, int year) {
  return String.format("%02d-%02d-%d", month, day, year);
}

Neat! I wonder, what other tricks could save developers like me from writing unnecessary and potentially copied code?

No comments:

Post a Comment