Sunday, June 05, 2016

enums IV

So you find yourself calling values() lots in your code. Since this allocates a new array every time and this does not get optimized away, you might want to create a local copy, or an immutable collection and use that instead:

public enum Day {

  private static final Day[] values = values();


or alternatively use an immutable Set.

Thursday, May 26, 2016

enums III

Enums have a name() method. And it has a very precise meaning. Now imagine:
public enum Day {
  MONDAY("code1"), TUESDAY("code2");

  private final String code;
  private Day(String code) {
    this.code = name;

  public String getName() {
    return code;
Now good luck finding out what is and what is Day.getName(). You'd be much better off calling this other method of yours getCode(). If name looks like a good name for your attribute, think long and hard to find an alternative.

enums II

public enum Days {
Then is it:
Days day = MONDAY;
or is it:
Days days = MONDAY;
How about a set of days? Would you call it days? Is it a set of days or a set of dayss? It can get worse: DaysEnum or DayEnums? Don't call your day days... To be fair such atrocities already exist in jdk, like LayoutFlags or CssFlags (these particular ones thankfully in the bowels of com.sun.javafx). Not one of their best moments.

enums I

Imagine Month being MonthEnum. What is Monday? A month? Or a monthEnum? Do everyone a favour then and stop calling your enums, well, enums.