In Dart, is there a better solution than a large switch statement

Viewed 74

I have a large multi-level switch statement that I'm using to take a table/field ID combination and return a string. Is there a system in dart that is a better choice in regards to read-ability and performance than a switch statement? Is there anything like a mapping or something that I should be using?

This is a snippet of the switch statement which will have 100s of lines when it is done.

switch (tableID)
    {
        case DBTables.Abbreviations:
            switch (fieldID)
            {
                case TBAbbreviations.ID: result = 'Record ID'; break;
            }
            break;
        case DBTables.Activity:
            switch (fieldID)
            {
                case TBActivity.ID: result = 'Record ID'; break;
                case TBActivity.Nickname1: result = 'Nickname'; break;
                case TBActivity.Nickname2: result = 'Nickname 2'; break;                    
                case TBActivity.FullName: result = 'Fullname'; break;                    
                case TBActivity.Classification: result = 'Classification'; break;                    
            }
            break;
    }

    return 'Field Name: ' + result ;    
1 Answers

You don't write what type tableID and fieldID are but I am guessing they are both int.

I have made the following example which tries to split up the responsibility of the mapping so each table class does its own mapping:

class DBTables {
  static const int Abbreviations = 1;
  static const int Activity = 2;

  static String lookupFieldName(int tableID, int fieldID) {
    String result;

    if (tableID == Abbreviations) {
      result = TBAbbreviations.idToString[fieldID];
    } else if (tableID == Activity) {
      result = TBActivity.idToString[fieldID];
    }

    return 'Field Name: $result';
  }
}

class TBAbbreviations {
  static const int ID = 1;

  static const Map<int, String> idToString = {ID: 'Record ID'};
}

class TBActivity {
  static const int ID = 1;
  static const int Nickname1 = 2;
  static const int Nickname2 = 3;
  static const int FullName = 4;
  static const int Classification = 5;

  static const Map<int, String> idToString = {
    ID: 'Record ID',
    Nickname1: 'Nickname',
    Nickname2: 'Nickname 2',
    FullName: 'Fullname',
    Classification: 'Classification'
  };
}

void main() {
  print(DBTables.lookupFieldName(DBTables.Activity, TBActivity.FullName)); // Field Name: Fullname
}

You can discuss the placement of DBTables.lookupFieldName but I think it makes sense for my small example.

Related