jeudi 24 juin 2021

Refactor if conditional blocks with multiple returns

In one of the applications, had to execute tasks in a sequential manner. There are 'n' number of tasks and they need to be executed if the previous task is completed successfully - tracked by the status variable.

The multiple if conditions in the method looks ugly and need to be replaced by some sort.

public boolean process() {
  String status;
  status = doTask1();
  if (StringUtils.equals(status, "error")) {
    return true;
  }
  status = doTask2();
  if (StringUtils.equals(status, "error")) {
      return true;
  }
  status = doTask3();
  if (StringUtils.equals(status, "error")) {
    return true;
  }
  return false;
}

Aucun commentaire:

Enregistrer un commentaire