Favoring split method Over StringTokenizer

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new codes. The recommended replacement is to use the split method of String or the java.util.regex package instead. If possible, legacy codes using the StringTokenizer class should be refactored.

Example:
We’ve a method to convert a String represented time value (e.g., 1.25 hours) that means to be reformatted into a new format (01:15).

public String getTimeFormattedString(String time) {
  String timeDisplay = null;
  if (time.indexOf(".") != -1) {
    String hour = "";
    String minutes = "";
    String min = "";
    StringTokenizer str = new StringTokenizer(time, ".");
    while (str.hasMoreTokens()) {
      hour = str.nextToken();
      minutes = str.nextToken();
    }
    minutes = "0." + minutes;
    int mts = (int) Math.round(Double.parseDouble(minutes) * 60);
    if (hour.length() < 2) {
      hour = "0" + hour;
    }
    if (new Integer(mts).toString().length() < 2) {
      min = "0" + new Integer(mts).toString();
    } else {
      min = "" + mts;
    }
    timeDisplay = hour + ":" = min;
  } else {
    if (time.length() < 2) {
      time = "0" + time;
    }
    timeDisplay = time + ":00";
  }
  return timeDisplay;
}

To refactor by using the split method of String:

public String getTimeFormattedString(String time) {
  String timeDisplay = null;
  if (time.indexOf(".") != -1) {
    String[] duration = time.split("\\.");
    String hrs = (duration[0].length() == 1 ? "0" + duration[0] : duration[0]);
    int minutes = (int) Math.round(Double.parseDouble("0." + duration[1]) * 60);
    String mins = (minutes < 10 ? "0" + minutes : "" + minutes);
    timeDisplay = hrs + ":" + mins;
  } else {
    timeDisplay = time + ":00";
  }
  return timeDisplay;
}

The refactored method is significantly shorter, easier to understand & maintained. Of course, with proper database design, the time component should have been represented as a DATE or TIMESTAMP rather than with a VARCHAR.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: