Dave's Brain

Browse - Programming Tips - What's a good way to manage a group of boolean options that I am passing to a method in Java?

Date: 2012may2
Language: Java


Q.  What's a good way to manage a group of boolean options that I am passing to a method in Java?

A.  Use a BitSet.

Make some names of the bits:

static final int OPTION_A = 0; // The first bit represents option A (whatever that is) static final int OPTION_B = 1; static final int OPTION_C = 2; static final int OPTION_D = 3;
Declare your function as so:
myfunction(BitSet options) { if (options.get(OPTION_B)) { // Do option B things } }
And call it this way:
BitSet myoptions = new BitSet(); myoptions.set(OPTION_A); myoptions.set(OPTION_C); myfunction(myoptions);
The ugly alternative using booleans:
myfunction(boolean option_a, boolean option_b, boolean option_c, boolean option_d) { if (option_b) { // Do option B things } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.