Flags enum & bitwise operations vs. “string of bits”

Benefits of using Flags enum:

  • Standard approach: “They are the correct design to use when multiple enumeration values can be specified at the same time.”
  • Intent is clear
  • Maintainable — new programmers should pick this up easily
  • Easily extensible — support for new flag combinations (e.g. weekend)
  • Fast

Negatives of using Flags enum:

  • Data representation for humans hard to understand (e.g. what flags are set for 17?)

Benefits of using string of bits:

  • Easy for programmers to see which bits are set in string

Negatives of using string of bits:

  • Non-standard approach
  • Harder to understand for programmers unfamiliar with your design
  • Potentially easier to set “garbage” values (e.g. stringValue = “Sunday”)
  • Needless string creation
  • Needless string parsing
  • Additional development work
  • Reinventing the wheel (but not even a round wheel)

How important is it really to be able to look at the string of bits to see what is set? If it’s hard to know that 17 is Monday and Friday, you can always use calculator and convert to binary. Or add some sort of string representation for “display” (or debugging) use. It’s not that difficult.

It also seems to me that if you are going to make the string of bits approach solid then you will need to do quite a bit of encapsulation to bring it up to a level of abstraction that the Flags enum already provides. If the approach is to simply manipulate the string of bits directly then that is going to be hard to read (and understand) and probably error prone.

e.g. you may end up seeing this:

days = "1000101"; // fixed bug where days were incorrectly set to "1010001"

Leave a Comment

tech