开发者

Which of the following technique is better? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

Let's say I have three conditions: Condition1, Condi开发者_JAVA技巧tion2, Condition3. If all the conditions are fulfilled then the method/function returns true else false.

Technique one:

     function check(){
        if(Condition1 is true AND Condition2 is true AND Condition3 is true){
           return true;
        }
        return false;
     }

Technique two:

      function check(){
         if(Condition1 is false){
             return false;
         }
         if(Condition2 is false){
             return false;
         }
         if(Condition3 is false){
             return false;
        }

         return true;
      }

Which of the techniques would be better?


"Better" is subjective.

return (Condition1 && Condition2 && Condition3); // "Better" yet?

Depends on what's more readable, and maintainable, in the non-contrived code.

Personally, I'm a fan of returning as early as possible, when it makes sense to do so and it increases readability.


I would use technique 3:

 function check() {
    return Condition1 && Condition2 && Condition3;
 }

No need to compare to true or even have an if block.


function check(){
    return (Condition1 && Condition2 && Condition3);
}

I think it's better to have a unique return statement in a method.


The top one is better, it will short circuit anyway. That means that if condition1 is false it won't check condition2 or condition3, so you don't save anything with the second method.

Also, skip the "is true" bit, you can just do:

return (Condition1 && Condition2 && Condition3)


function check() {
  return condition1 && condition2 && condition3;
}

The simplest solution is to find the value of the boolean and express and return that.

What is probably the most optimum solution is the following

function check() {
    var usefulConditionName = /* long condition */;
    var secondUsefulConditionName  = /* long condition */;

    return (usefulConditionName &&
        secondUsefulConditionName);
}


I usually think the less code and duplication, the better. I might go with

function check()
{
    return Condition1  AND Condition2  AND Condition3 ;
}


Neither. The best option is to return the value of the expression directly. There is no need for more verbosity. Also, JavaScript doesn't have AND operator, it has &&.

function check() {
   return Condition1 && Condition2 && Condition3;
}


IMHO I prefer the first technique, because : 1- Less line of code 2- Less return.

But everyone can have different opinion on question like this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜