This code looks highly repetitive and I suspect there's a much cleaner way of writing it, but it's not coming to mind. Does anyone have any suggestions?
(It's title() that concerns me, not dividesWell() or format(), although I'm open to any suggestions that anyone has for either of those. I just included them for completeness, since title() references both of them.)
(It's title() that concerns me, not dividesWell() or format(), although I'm open to any suggestions that anyone has for either of those. I just included them for completeness, since title() references both of them.)
Code:
/**
* Determines a title based on simplifying the units of the duration.
*/
private String title(long seconds) {
long minutes = dividesWell(seconds, 60);
if (minutes != 0) {
long hours = dividesWell(minutes, 60);
if (hours != 0) {
long days = dividesWell(hours, 24);
if (days != 0) {
long years = dividesWell(days, 365);
if (years != 0) {
return format(years, "Year");
}
long weeks = dividesWell(days, 7);
if (weeks != 0) {
return format(weeks, "Week");
}
return format(days, "Day");
}
return format(hours, "Hour");
}
return format(minutes, "Minute");
}
return format(seconds, "Second");
}
/**
* Returns round(a/b) if it's a close approximate of a/b, or 0 if it's not.
*/
private long dividesWell(long a, long b) {
double actual = (double)a/(double)b;
long approximate = Math.round(actual);
double error = Math.abs((actual - approximate) / actual);
return error < 0.009 ? approximate : 0;
}
/**
* Writes the number and the unit, pluralized if appropriate.
*/
private String format(long a, String unit) {
return a + " " + unit + (a != 1 ? "s" : "");
}