nazar_art nazar_art - 5 months ago 18
Java Question

Modifying else if and | operators

I have this snippet of code and want to know if exist way to make it much more readable?

My code:

public String getMonthName()
{
if (1 == this.monthNumber) {
monthName = "January";
} else if (2 == this.monthNumber) {
monthName = "February";
} else if (3 == this.monthNumber) {
monthName = "March";
} else if (4 == this.monthNumber) {
monthName = "April";
} else if (5 == this.monthNumber) {
monthName = "May";
} else if (6 == this.monthNumber) {
monthName = "June";
} else if (7 == this.monthNumber) {
monthName = "July";
} else if (8 == this.monthNumber) {
monthName = "August";
} else if (9 == this.monthNumber) {
monthName = "September";
} else if (10 == this.monthNumber) {
monthName = "Oktober";
} else if (11 == this.monthNumber) {
monthName = "November";
} else if (12 == this.monthNumber) {
monthName = "December";
}

return monthName;
}

/**
* Gets the number of days in this month
* @return the number of days in this month in a non-leap year
*/
public int getNumberOfDays()
{
int numberOfDays;
if (monthNumber == 1 || monthNumber == 3 || monthNumber == 5 || monthNumber == 7 || monthNumber == 9 || monthNumber == 11) {
numberOfDays = 31;
} else if (monthNumber == 4 || monthNumber == 6 || monthNumber == 8 || monthNumber == 10 || monthNumber == 12) {
numberOfDays = 30;
} else {
numberOfDays = 28;
}

return numberOfDays;
}
}


How better way to refactoring code? Make it much more readable.

Answer

Use enum

public enum Month
{
  JANUARY( "January", 31 ),
  FEBRUARY( "February", 28 ),
  ...
  DECEMBER( "December", 31 );

  private String monthName;
  private int numOfDays;

  private Month ( String monthName, int numOfDays )
  {
    this.monthName = monthName;

    this.numOfDays = numOfDays;
  }

  public String getDisplayName ( )
  {
    return monthName;
  }

  public int getNumOfDays ( )
  {
    return numOfDays;
  }
}
Comments