开发者

As related to maintainability are mapping tables a better design than a 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. Once I've identified a symbol I end up at a case statement that decides which translation routine to call depending on what the user selected input option was (these are codes that mean different things on different machines).

I am essentially taking multiple input formats and converting them to a single output format, over about 400 unique symbols.

The problem is that as this project has grown from a couple of simple translations, each in its own header file, into a dozen or more input formats it is getting cumbersome to maintain. Each of these开发者_StackOverflow中文版 header files contains a monster switch statement that produces the relevant output. It all works but really seems clumsy.

Will I resolve the maintainability issue by creating mapping tables ( ie a 2d array containing input and output symbols ) for each input machine and using a common translation routine taking the tables as input? Is there a better design I should consider?


A hash-table type structure would definitely be easier to maintain but there is at least one tradeoff, namely that your giant switch statement would almost certainly be faster because any decent compiler would optimise it into a jump table. But it (depending on the implementation) it shouldn't be that noticably slower unless you're doing 50 billion lookups or something. That said, a hash table could be optimised to be just as fast as a switch statement.

Bottom line: if you don't need to be sure that you're getting every ounce of speed possible, then I'd go with a hash table. If it matters, profile.

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


You can use macros to reduce code duplication. For example

#define ENTRY(ID, OUT) case ID: write_to_output(out); break;

switch (id) {
   ENTRY(ID1, "ID1");
   ENTRY(ID2, "ID3");
   ENTRY(ID2, "ID3");

   default:
     ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜