语句的长条件语句

语句的长条件语句

本文介绍了如何缩进'if'语句的长条件语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与有关,但是所提供的解决方案没有解决我在下面概述的问题。在google搜索后,我没有找到任何代码风格的指导方针,解决了这种if语句中长条件语句的具体问题。

My question relates to this previous question, but the solutions offered don't address the problem I have outlined below. After a google search I haven't found any code style guidelines that address the specific problem of long conditionals in an if statement like this.

if( isNull(value1) ||
    isToLong(value1) ||
    hasBadFormat(valule1)){
    doSomething();
}else{
    doSomethingElse();
}

或:

if( isNull(value1) || isToLong(value1) || hasBadFormat(valule1) ){
    doSomething();
}else{
    doSomethingElse();
}

我对这两种风格的问题是,在真正的块中找到代码并将其与条件分开,或者对于眼睛来说,很难在单个行上的长条件之后确定正确的下一行,特别是如果if语句已经缩进了几个选项卡函数或其他if语句。

The problem I have with these two styles is it makes it hard for my eye to find the code in the true block and separate it from the conditionals, or it is too difficult for the eye to determine the correct next line after a long conditional on a single line, especially if the if statement is already indented a few tabs inside a function or other if statements.

最好这样做:

if(     isNull(value1) ||
        isToLong(value1) ||
        hasBadFormat(valule1)){
    doSomething();
}else{
    doSomethingElse();
}

或者这种风格会更好地缩进每种新条件:

or would this style be better to indent each new condition in either of these ways:

if( isNull(value1) ||
        isToLong(value1) ||
            hasBadFormat(valule1)){
    doSomething();
}else{
    doSomethingElse();
}

if( isNull(value1)
        || isToLong(value1)
            || hasBadFormat(valule1) ){
    doSomething();
}else{
    doSomethingElse();
}

有没有人有一个编码风格指南以与我提出的不同或更好的方式解决这个问题?

Does anyone have a coding style guideline (maybe a company coding style policy) that addresses this issue in a different or better way than I've proposed? Which one is preferable and can you find any cons or pros to the solutions I've mentioned?

推荐答案

这样的事情怎么样? ?

How about something like this?

bool isValid = isNull(value1) || isToLong(value1) || hasBadFormat(valule1);
if( isValid )
{
   doSomething();
}
else
{
   doSomethingElse();
}

条件被移动到另一行,这可能更容易阅读。

The conditional gets moved onto another line, which might make it easier to read.

这篇关于如何缩进'if'语句的长条件语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:12