Using enum can greatly increase the readability of the code and it may significantly reduce the complexity as well. Let us start with some code not using enum,
DateUtils.getDate(2012, 5, 6)
It is not clear which month it is. Does it mean May or June? Worse thing is in one library it may mean May and in another library it means June.
I added another method to make the following call possible, with static import in Java, it look like this,
date(June, 6, 2012)
I believe even non technical people can read it and understand now, it make the code much easier to understand.
public enum Months {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December;
}
I don't need to rewrite new method, I just need to call the old method in the new method,
static Date date(Enum month, int day, int year) {
DateUtils.getDate(year, month.ordinal(), day)
}
Sometimes, on the web layer, the month may be spelled as a short form, then we can introduce another enum,
public enum ShortMonths {
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec;
}
We can pass this ShortMonths and make the call like this,
date(Jun, 6, 2012)
DatePicker uses this pattern.
No comments:
Post a Comment