Often a class has to be configured using a number of boolean options. What are recommended ways in Java to specify execution configurations?
I can think of 4 ways how options can be passed to the class.
-
Using bitmasks. Efficient, easy to use, but not grouped together. More difficult to find via autocomplete amongst other members. Restricted in size.
public static final int A_ENABLED = 1 << 1; public static final int B_ENABLED = 1 << 2; -
Using (inner) parameter class. Difficult to create, too verbose.
public static class Params { private final boolean enabledA; private final boolean enabledB; } public class MyFunctionality { private final SomeOtherArguments myDataArguments; ... private final Params params; MyFunctionality(SomeOtherArguments myDataArguments, Params params); } -
Using boolean fields as part of the class. Increases verbosity of the class (extra arguments in the constructor you have to worry about). Constructor of the class has to be modified everytime parameters change. In 2 option only Params class will change.
public class MyFunctionality { private final SomeOtherArguments myDataArguments; ... private final boolean enabledA; private final boolean enabledB; private final boolean enabledC; private final boolean enabledD; ... public MyFunctionality(SomeOtherArguments someOtherArguments, boolean enabledA, boolean enabledB, boolean enabledC, boolean enabledD); } -
Using enums.
public static enum Params { OPTION_A, OPTION_B }
Can you think of other better ways to do that?
Enums and the EnumSet are specifically designed for this.
optionSet contains the options that are ‘set’. EnumSet is extremely efficient, using just one bit for each enum element in most implementations, and allowing get and set in constant time. You can of course restrict setting options to construction time as well.
EDIT: You can set multiple options such as A and B simultaneously with: