Using 'return' instead of 'else' in JavaScript

后端 未结 13 1745
無奈伤痛
無奈伤痛 2020-12-01 14:09

I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if-elses in quite a few places.

13条回答
  •  悲哀的现实
    2020-12-01 14:47

    I will use the first approach when ruling out the invalid situations.

    Eg. use first approach when doing some validations, and return if any of the validation fails. There's no point in going further if any of the preconditions fail. The same thing is mentioned by Martin fowler in his Refactoring book. He calls it "Replacing the conditions with Guard clauses". And it can really make the code easy to understand.

    Here's a java example.

      public void debitAccount(Account account, BigDecimal amount) {
        if(account.user == getCurrentUser()) {
          if(account.balance > amount) {
               account.balance = account.balance - amount
           } else {
              //return or throw exception
           }
        } else {
            //return or throw exception
        }
      }
    

    VS

     public void debitAccount(Account account, BigDecimal amount) {
        if(account.user != getCurrentUser()) return //or error
        if(account.balance < amount) return //or error
        account.balance = account.balance - amount    
    }
    

提交回复
热议问题