Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lots of boolean flag inputs to a class

I have a dialog that displays various things depending on state of the application, security for the current user etc. I am currently passing in several boolean flags and then enabling and/or hiding UI components depending on these flags.Eg:

new MyDialog(showOptionsTable, allowFooInput, allowBarInput, isSuperUser) 

Initially this started out as a couple of flags and that was fine. But now with changing requirements, it has evolved into an input of five boolean flags.

What is the best practices way of handling behavior like this? Is this something that I should subclass depending on how the dialog should look?

like image 581
Kapsh Avatar asked May 08 '09 18:05

Kapsh


2 Answers

As with many things, "it depends".

  1. Ben Noland suggested a class to hold configuration options. This is doable, but favor immutability, and optionally use the builder pattern. Because booleans are built-in types, writing a small builder will really help people understand the code. If you compare this to MyDialog(true, true, ...) you know what I mean:

    Options.allowThis().allowThat().build()

  2. Chris suggested bit fields, but as some of the commenters point out, bit fields are evil because of many reasons outlined in Josh Bloch's Effective Java. Basically they are hard to debug and error prone (you can pass in any int and it will still compile). So if you go this route, use real enums and EnumSet.

  3. If you can reasonably subclass (or compose), meaning that you usually only use a couple of combinations of all the booleans, then do that.
like image 62
RobbieV Avatar answered Oct 11 '22 19:10

RobbieV


Once you get more than two or three flags, I would consider creating a class to store these settings to keep your design clean.

like image 34
Chris Ballance Avatar answered Oct 11 '22 18:10

Chris Ballance