C ideas for reducing this feature?

I have this huge case of switching with nested case case statements in it, which I was wondering if anyone has any ideas on cleaning up?

switch (datatype) {
    case STR:
    {
         switch(operation)
         {
              case EQUALS:
              {
                     /* perform str compare */
              }
              case NOTEQUALS:
              {
              }
              case LT:
              {
              }
              case GT:
              {
              }
              case GTE:
              {
              }
              case LTE:
              {
              }
              default:
                 break;
         }
         break;
    }
    case VER:
    {
         switch(operation)
         {
              case EQUALS:
              {
                     /* perform version compare */
              }
              case NOTEQUALS:
              {
              }
              case LT:
              {
              }
              case GT:
              {
              }
              case GTE:
              {
              }
              case LTE:
              {
              }
              default:
                 break;
         }
         break;
    }
    case INT:
    {
         /* same */
    }
    case FLOAT:
    {
         /* same */
    }
    /* ... more types ... */
    /* ... .......... ... */
    default:
        break;
}
+3
source share
7 answers

If the operation values ​​are contiguous, you can create a table of function pointers. In fact, you can create a 2D table of function pointers with a separate function to handle each combination of operations / types. eg

// do some range checking on input params
// invoke the handler
handlers[datatype][operation]();
+11
source

Create some tables (arrays) with pointers to functions in it. Then you can find func[STR][EQUALS]to make the corresponding call. The call will look like this:

Func[datatype][operation]();
+5
source

.

+2

NOTEQUALS EQUALS; GTE LT LTE GE. operation, datatype.

+2

, , , .

0

?

, - :

bool someArbitraryFunction (dataType aDatatype, operations anOperation)
{
 someUnknownStruct.datatype = aDatatype;
 someUnknownStruct.operation = anOperation;
 return someUnknownStruct->doMath(1,2);
}

, -.

"" ( , ).

0

, , LT EQUALS, :

switch(operation) {
  case EQUALS:
    return isEquals();
  case NOTEQUALS:
    return !isEquals();
  case LT:
    return isLT();
  case GT:
    return !isLT() && !isEquals();
  case GTE:
    return !isLT();
  case LTE:
    reutrn isLT() || isEquals();
  default:
    break;
}

, isLT() isEquals(), . , .

, , switch().

0

Source: https://habr.com/ru/post/1719742/


All Articles