4

I was trying to be smart and elegant, and I ended up shooting myself in the foot by coding my entire application to use flags to store various combinations of settings.

Now, I have hit a point where I have > 64 options. I need to move away from flags or I will be forced to create additional fields, which will make my application really messy given its current state.

What should I consider as an alternative to using flags other than creating a separate boolean variable for each option?

Update

By flags, I mean bitwise flags, e.g.:

[Flags]
public enum Time
{
    None = 0
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4,
    // ...
    Flag63 = ...
}
0

You could use a BitArray in conjunction with static fields to provide labels for the bits:

static class Flags
{
  public static int WorkProperly = 0;
  public static int CompileFaster = 1;
  public static int AutoImproveCodeQuality = 2;
}

class FlagTest
{
  static void Main(string[] args)
  {
    BitArray bits = new BitArray(100); // > 64
    bits[Flags.AutoImproveCodeQuality] = true;
  }
}

Or, with an enum, but you'd have to cast the value every time:

enum Flags
{
  Never = 0,
  MostOfTheTime,
  Sometimes,
  OddThursdays,
  WhenPigsFly
}

...

BitArray bits = new BitArray(1000); // lots of bits
bits[(int)Flags.Sometimes] = true;
  • 6
    Please do not use a BitArray for your options, as you will lose almost all compiler checks. – Frank Kusters Oct 28 '14 at 5:55
5

If you have a lot of options, figure out if you can:

  • reduce the number. How about making an assumption instead of making something configurable?
  • group the options together. See this answer to Is a single config object a bad idea?:

    If you need to change the config class you may have to visit every instance in which it is used and check that you haven't broken anything.

    One way to deal with this is to create multiple interfaces that expose parts of the config object that are needed by different parts of the app. Rather than allowing other classes to access the config object, you pass instances of an interface to the classes that need it. That way, the parts of the app that use config depend on the smaller collection of fields in the interface rather than the whole config class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.