Working with a severely limited interpreted language

橙三吉。 提交于 2019-12-11 01:37:11

问题


I'm coding in an embedded language called JS.

I want to be able to call three functions in any order. (ABC, ACB, BAC, BCA, CBA, CAB.)

The trick? The language doesn't have user-defined functions.

It does have a conditional and a looping construct.

I think I have three choices.

  1. Duplicate a whole bunch of code.
  2. Write a preprocessor (that would create all the duplicated code).
  3. Do a loop with three iterations, using an array to control which functionality gets called on each pass of the loop.

I hate #1. Duplicated code is nasty. How do I change anything without screwing up?

I guess #2 is OK. At least I don't have duplicated code in the source. But my output code is what I'll be debugging, and I wonder if I want to diverge from it. On the plus side, I could add a bunch of sugar to the language.

I think my best bet is #3.

Any other ideas? There is no goto. No functions. No existing preprocessor.

Funny thing about #3 is that it's essentially the infamous for/switch nightmare.


回答1:


Perhaps some kind of mutant state-machine, viz:

int CODEWORD=0x123;

while (CODEWORD)
{
    switch(CODEWORD&15)
    {
    case 1:
       /// case 1
       break;
    case 2:
       /// case 2
       break;
    case 3:
       //// case 3
       break;
    }
    CODEWORD=CODEWORD>>4;
}

DRY, no preprocessor, no array. for/switch seems somewhat unavoidable.




回答2:


You might be able to use the C preprocessor instead of writing your own. That would at least let you try it to see if it's a workable solution.




回答3:


The technically best solution (assuming that you have access to the code or the developers) is to modify the JS language to do what you really need.

Failing that, the best solution depends on aspects of the problem that you haven't explained:

  1. are the 'functions' recursive?
  2. are there function parameters?
  3. do you need (are you likely to need) other control structures not provided in JS?
  4. does the function call order depend on runtime parameters?
  5. are you skilled and confident enough to design and implement a preprocessor language that meets your current and projected requirements?
  6. is implementing a preprocessor going to save you / coworkers time in the long run?

If the answers to 5. and enough of the others are "yes", then your option #2 is the right answer. Otherwise ... an ugly solution like your #1 or #3 might actually be a better idea.

EDIT: If you don't have source code access and the development team is not responsive to your needs, consider looking for an open-source alternative.



来源:https://stackoverflow.com/questions/1148979/working-with-a-severely-limited-interpreted-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!