开发者

Optimize nested if statements

Is their a simpler way to emulate this logic?

Every single method being called return True or False if any of the following methods returns a False then the this.displayError() method gets called.

I can't think of a simpler emulating this logic, any thoughts?

     main: function(){
    if(this.isWRNotProcessed()){
        if(this.retriveWRMetaData()){
            if(this.retrieveWRLines()){
                this.getDistinctOrders();
                if(this.createNewPOs()){
                    this.approvePOs();
                } else{this.displayError();}
            } else{this.displayError();}
        } else{this.displayError();}    
    } else{this.displayError();}
      }

EDIT: Added an additional else statement when invoking this.createNewPOs() Sorry about that, and thanks for all the responses they are all helpful!

Also could a Try Catch statement work on this logic instead of I开发者_StackOverflowFs?


This should do what you want:

main: function () {
    if (this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines()) {
        this.getDistinctOrders();
        if (this.createNewPOs()) {
            this.approvePOs();
        }
    } else {
        this.displayError();
    }
}


Probably it becomes more readable like this:

main: function()
{
   var is_valid = 
      this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines();

   if(!is_valid)
   {
      this.displayError();
      return;
   }

   this.getDistinctOrders();

   if(this.createNewPOs())
   {
      this.approvePOs();
   }    
}


main: function(){
  if (this.isWRNotProcessed() && this.retrieveWRMetaData() && this.retrieveWRLines()){
    this.getDistinctOrders();
    if (this.createNewPOs()){
      this.approvePOs();
      return
    }
  }
  this.displayError();
}

Or am I missing something? Unless displayError gets specific to the failure, this should work for your purpose.


to simplify readability I would make one more method... It is just logical, that if you make something when this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines() is true then there should be explanation what altogether it means.

 someCheck: function(){ // I don't know what exactly it does so call this way..
     return this.isWRNotProcessed() 
          && this.retriveWRMetaData()
          && this.retrieveWRLines();
 },

 main: function(){
     if(this.someCheck()){
            this.getDistinctOrders();
            if(this.createNewPOs()){
                this.approvePOs();
            }
     } else {
             this.displayError();
     }
 }


Maybe this:

if(this.isWRNotProcessed() && this.retriveWRMetaData() && this.retrieveWRLines() &&     this.getDistinctOrders() && this.createNewPOs()) {
     this.approvePOs();
} else {
     this.displayError();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜