Use enumeration to simplify the statistics of multiple flag bits

The product in the recent project put forward a requirement: a selection box is added to the page, and there are six check boxes for users to choose. After selecting, click OK to record the status of these six flags and add a log for the user's selection.

First of all, I am a rookie, and the code I wrote is simple and rude, which can be regarded as meeting the needs of the product. Then the code was submitted to the boss of the department, and was criticized and rejected. The boss is good, and he also gave his own solution. This method is really good. It is the perfect solution to the problem with enumeration and a switch-case function.

An enumeration is defined like this:

enum EWarnType
{
  EWT_One    = 0x00000001,
  EWT_Two    = 0x00000002,
  EWT_Three  = 0x00000004,
  EWT_Four   = 0x00000008,
  EWT_Five   = 0x00000010,
  EWT_Six    = 0x00000020,
  _C_MAX_NUM, }

The switch-case function is defined as follows:

std::string getString(int value)
{
    switch(value)
    {
    case EWT_One:
        return "one";
    case EWT_Two:
        return "two";
    case EWT_Three:
        return "three";
    case EWT_Four:
        return "four";
    case EWT_Five:
        return "five";
    case EWT_Six:
        return "six";
    default:
        return "one";
    }
}

The advantage of this is that the code will not be repeated, which is convenient for adding new functions and maintenance later.

 

1. Add these tags to the page You can do this:

int nFlag = EWT_One;
int i = 0;
while (nFlag < _C_MAX_NUM)
{
    //...do something

    ++i;
    nFlag = EWT_One << i;
}

Get it done in a loop. To add new options and maintenance in the later stage, you only need to add enumeration values ​​and modify the switch-case function.

 

2. Record the user's choice and use an int type to get it

int nValue = 0 ; // Record the state currently selected by the user 
int nFlag = EWT_One;
 int i = 0 ;
 while (nFlag < _C_MAX_NUM)
{
    if (...) // if the user selects this state nValue 
        |= nFlag;

    ++i;
    nFlag = EWT_One << i;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324674387&siteId=291194637