Regarding maintainability, is the mapping table better than the large switch statement?

I am translating text files from one set of definitions to another, and I solved the problem by writing a small parser. After I defined the character, I end up in a case case, which decides which translation procedure to call depending on which user has chosen the input option (these are codes that mean different things on different machines).

I use several input formats and convert them to one output format, more than 400 unique characters.

The problem is that since this project has grown from several simple translations, each in its own header file, to dozens or more input formats, it becomes cumbersome to maintain. Each of these header files contains a monster switch statement that outputs the corresponding output. It all works, but it actually seems awkward.

Will I solve the maintainability problem by creating mapping tables (i.e., a 2nd array containing input and output characters) for each input device, and using a general translation procedure that takes tables as input? Is there a better design I should consider?

+4
source share
2 answers

A hashtable-type structure will definitely be easier to maintain, but there is at least one trade-off, namely that your giant switch statement will almost certainly be faster, because any decent compiler will optimize it for the jump table. But this (depending on the implementation) should not be so noticeably slower if you are not doing 50 billion searches or something else. However, a hash table can be optimized as quickly as a switch statement.

Bottom line: if you don't need to be sure that you get every ounce of speed, I would go with a hash table. If that matters, profile.

You might want to check out gperf , which generates perfect compile-time hash tables.

+5
source

You can use macros to reduce code duplication. for instance

#define ENTRY(ID, OUT) case ID: write_to_output(out); break; switch (id) { ENTRY(ID1, "ID1"); ENTRY(ID2, "ID3"); ENTRY(ID2, "ID3"); default: .... } 
0
source

All Articles