Monday, January 3, 2011

Javascript Doesn't have Goto

Think that Goto is never needed in code?

Here:

if (conditionA) {
   if (conditionB) {
      if(conditionD) {
         codeD();
      }
   } else {
      codeNotB();
   }
} else {
   if (conditionC) {

      // wouldn't it be nice to put a Goto to the test in conditionD above?
      if(conditionD) {
         codeD();
      }
   } else {
      codeNotC();
   }
}

I'm encountering exactly this.  Obviously I could add a function - but it's messy when there are many nested for loops and variables that will have to be passed, and a Goto would be so simple.  Sorry - not in Javascript.

Wish I had switched to C# (which does support goto).  Ugh!

3 comments:

  1. I suppose the solution is to add booleans set where the redundant code is, and are re-tested later for running the redundant code. This avoids having to add a function.

    ReplyDelete
  2. or re-write the logic. But it's less readable:

    if ((conditionA && conditionB) || (!conditionA && conditionC)) {

    if (conditionD) {
    codeD();
    }

    }
    etc.

    ReplyDelete
  3. actually this forced me to write much prettier code. I would have to check if it's equivalently efficient, but it's certainly more readable. All those conditions had to be declared as boolean assignments (including all code redundancy), and then the re-written logic (as previous post).

    I know that in 2 years when I come back to this code, it won't give me heart-attack, while written in its original expanded form it would be more grotesque.

    ReplyDelete