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?
As with many things, "it depends".
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()
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.
Once you get more than two or three flags, I would consider creating a class to store these settings to keep your design clean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With