Search code examples
c#flagsreadability

How to improve maintainability and readability of flags


I have inherited some code that I need to maintain with a server and client. Certain settings are currently passed on to the client via a set of flags of an in-house binary protocol. e.g.,

if (object.has.someAttribEnum == SYS_ON)
  settingsFlag = settingsFlag | 2;
...
...
if(foo.has.someAttribEnum == DISP_ON)
  settingsFlag = settingsFlag | 4398046511104;

These settings are getting quite massive, since the flag is UInt64, so we are at 2^45. And also this function is betting quite huge. It is easy for developers to make mistakes such as using a value not a power of two, breaking the entire settings flag received by the client.

The best solution is probably to be sending on a serialized object over the binary protocol? Due to some implementation and time constraints, this might not be immediately possible.

What could I do to improve the readability and manageability of this? I even started thinking of using shifts inline instead of the values i.e.,

if(foo.has.someAttribEnum == DISP_ON)
  settingsFlag = settingsFlag | (1 << 42);

I appreciated any thoughts on this.


Solution

  • You could use a [Flags] enum. It allows you to easily define an enum with with different options specified as different values (typically powers of 2) and supports operations for checking if an option is set in a given enum value;

    Example:

    [Flags]
    public enum MySettings : ulong
    {
        SYS_ON = 1 << 1,
        DISP_ON = 1 << 42,
    }
    
    if (settings.HasFlag(MySettings.SYS_ON))
    {
        //do something
    }
    

    You can also create/set settings like:

    MySettings settings = MySettings.SYS_ON | MySettings.DISP_ON