Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always run cleanup at the end of function?

Say I have this function (psuedo-code) :

function Foo() {

  let varThatRequiresCleanup = //something

  if(condition1) {
    return Error1;
  }

  if(condition2) {
    return Error2;
  }

  if(condition3) {
    return Error3;
  }
  //etc.. more ifs and important code.

  varThatRequiresCleanup.CleanUp();
  return Success;
}

Coming from the C++ & C world I would just implement the cleaning up in the destructor or use a goto but JavaScript doesn't have either.

How would I go about calling CleanUp() whenever Foo() returns?

Is the only method to call CleanUp() in every if that I return in?

like image 214
Hatted Rooster Avatar asked Dec 06 '25 04:12

Hatted Rooster


2 Answers

One alternative could be to use a function for the repeating code :

function Foo() {

  let varThatRequiresCleanup = //something

  function CleanUpAndReturn(returnValue) {
    varThatRequiresCleanup.CleanUp();
    return returnValue;
  }

  if (condition1) { return CleanUpAndReturn(Error1); }

  if (condition2) { return CleanUpAndReturn(Error2); }

  if (condition3) { return CleanUpAndReturn(Error3); }
  //etc.. more ifs and important code.

  return CleanUpAndReturn(Success);
}
like image 61
Slai Avatar answered Dec 08 '25 16:12

Slai


You can use a try-finally block:

function Foo() {
  let varThatRequiresCleanup = //something

  try {
    if(condition1) {
      return Error1;
    }

    if(condition2) {
      return Error2;
    }

    if(condition3) {
      return Error3;
    }
    //etc.. more ifs and important code.

    return Success;
  } finally {
    varThatRequiresCleanup.CleanUp();
  }
}
like image 37
Cepheus Avatar answered Dec 08 '25 16:12

Cepheus