I’m curious if there are any rules of thumbs or design patterns on when to use bitmasks to help improve code readability and/or maintainability.
One place I’ve seen them in the wild is when there are a few or more configuration parameters that need to be passed into a function.
I’m coming at this from an OOP perspective but the answer need not be constrained just to OOP.
I think bitmasks are mostly to improve time and space performance. From an OOP standpoint, whatever they represent can be encapsulated in a proper interface. In C#, you can take a look at flags enums for a convenient way to represent them as enumerations.
To pass configuration parameters to a method, I usually prefer creating a class. This way, you can have parameters that are more than just flags, and the client doesn’t need to worry about bitwise operations. Take a look at the
XmlWriterSettingsclass for an example. For an example of a flags enum, look at theRegexOptionsclass.