Best practice of using flags in Java method

Roalt picture Roalt · May 20, 2011 · Viewed 16.6k times · Source

What's the best practice for specifying flags in a Java method?

I've seen SWT using int as bitfields, like:

(example partially from "Effective Java, 2nd Ed." page 159):

public class Text {
  public static final int STYLE_BOLD = 1 << 0; // 1
  public static final int STYLE_ITALIC = 1 << 1; // 2

  void printText(String text, int flags) {

  }
}

and your client call looks like:

printText("hello", Text.STYLE_BOLD | Text.STYLE_ITALIC);

..but this is discouraged as you can mixed flags (int values) from different classes together without any compiler checks.

In the same book ("Effective Java"), I see the use of EnumSet, but then your user call becomes:

printText("hello", EnumSet.of(Style.Bold, Style.ITALIC));

I find this a bit verbose and I prefer the elegance of SWT.

Is there any other alternative or is this basically the two tastes you must pick?

Answer

Aravindan R picture Aravindan R · May 20, 2011

Guess you have hit a wall. I don't see any other option. Java is verbose that's a fact. In situations like this i usually add a local variable to make the code more readable. You can do this,

EnumSet<Style> styles = EnumSet.of(Style.Bold, Style.ITALIC);
printText("hello", styles);