skip to Main Content
void methodA() {
  if (1 == 1) {
    checkIfExitMethodA();
    doSomething();
  } else {
    print('nothing');
  }
}

void checkIfExitMethodA() => print('check whether to exit the parent function');

Is it possible to implement checkIfExitMethodA() method which contains few conditions to check and methods to exucate, and once it meets it will exit methodA() entirely?

It can be done by simply putting a return but I would like to exit by assessing checkIfExitMethodA() before doSomething.

2

Answers


  1. I guess the only way to do it is to throw exception.

    void checkIfExitMethodA() => assert(!conditionMet, 'condition met, parent handles...');
    
    Login or Signup to reply.
  2. The obvious way would be a return value to be checked:

    void methodA() {
      if (1 == 1) {
        if(checkIfExitMethodA()) {
          return;
        }
        doSomething();
      } else {
        print('nothing');
      }
    }
    
    bool checkIfExitMethodA() => /* your condition here instead of */ true;
    

    There is no "normal" way to tell the caller to exit their method. There is the "exceptional" way mentioned in another answer though, maybe that suits better you:

    void methodA() {
      if (1 == 1) {
        checkIfExitMethodA();
        doSomething();
      } else {
        print('nothing');
      }
    }
    
    void checkIfExitMethodA() {
      if(/* your exit condition*/ true) {
        throw Exception("Condition not met");
      }
    }
    

    Please note that this will not "exit method A". It will exit all methods until you implement a catch block.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search