Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice of using flags in Java method

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?

like image 617
Roalt Avatar asked Feb 02 '23 18:02

Roalt


1 Answers

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);
like image 134
Aravindan R Avatar answered Feb 05 '23 06:02

Aravindan R