控制结构逻辑的顺序是否正确(真/假、假/真)?

发布于 2024-07-07 23:22:38 字数 156 浏览 9 评论 0原文

我是编程新手,想知道是否有正确的方法来排序控制结构逻辑。

首先检查最可能的情况似乎更自然,但我有一种感觉,某些控制结构将无法工作,除非它们检查所有错误的内容以得出正确的结果(逻辑推论?),否则

很难适应这种“消极”观点,我更喜欢更积极的观点,假设一切都是真的:)

I am new to programming, and am wondering if there is a correct way to order your control structure logic.

It seems more natural to check for the most likely case first, but I have the feeling that some control structures won't work unless they check everything that's false to arrive at something that's true (logical deduction?)

It would be hard to adapt to this 'negative' view, I prefer a more positive outlook, presuming everything is true :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

烏雲後面有陽光 2024-07-14 23:22:38

McConnell 的 Code Complete 中对此主题进行了精彩的讨论。 这是我强烈推荐的一本书。 无论如何,相关讨论在第一版的第 706-708 页或第 708 页。 第二版 749-750(感谢底座)。 摘自那本书:

安排测试,以便
最快且最有可能是真的
首先执行。 应该很容易
下降到正常情况,如果
存在效率低下的情况,应该
正在处理异常。

There is an excellent discussion of just this topic in McConnell's Code Complete. It's a book that I highly recommend. Anyway the relevant discussion is on pages 706-708 of the first edition or pg. 749-750 of second edition (thanks plinth). From that book:

Arrange tests so that the one that's
fastest and most likely to be true is
performed first. It should be easy to
drop through the normal case, and if
there are inefficiencies, they should
be in processing the exceptions.

等你爱我 2024-07-14 23:22:38

除了条件语句的值之外,还有一些事情需要考虑。 例如,如果代码块的大小明显不同,您可能需要将小块放在前面,以便更容易查看。 (如果较大的块确实很大,则可能需要对其进行重构,或者可能将其提取到单独的方法中。)

if( condition is true ) {
    do something small;
} else { 
    do something;
    and something else; 
    . . .
    and the 20th something;
}

在条件内,是的,有些语言一旦表达式的一部分为假,就会停止计算表达式。 如果您在代码中包含某种定义的逻辑,记住这一点很重要:如果您的语言计算整个表达式,您应该这样做:

if( variable is defined ) {
    if( variable == value ) {
        ...
    }
}

而不是这样做:

if( (variable is defined) && (variable == value) ) {
     ...
}

我认为没有“正确”的设计方法你的条件。 如果您所在的公司有编码标准,您应该检查标准中是否包含该标准。 (我工作的最后一个地方定义了合理数量的标准,但没有指定如何编写条件逻辑。)

There are things to consider in addition to the value of the condition statement. For example, if the blocks of code are significantly different in size, you may want to put the small block first so that it is easier to see. (If the larger block is really large, it may need to be refactored, or perhaps pulled out into a separate method.)

if( condition is true ) {
    do something small;
} else { 
    do something;
    and something else; 
    . . .
    and the 20th something;
}

Within the condition, yes, there are some languages that will stop evaluating an expression once one part of it is false. This is important to remember if you include some sort of is-defined logic in your code: if your language evaluates the entire expression, you should do this:

if( variable is defined ) {
    if( variable == value ) {
        ...
    }
}

rather than this:

if( (variable is defined) && (variable == value) ) {
     ...
}

I don't think there is a "correct" way to design your conditions. If you are working for a company that has coding standards, you should check to see if that is included in the standards. (The last place I worked had a reasonable number of standards defined, but did not specify how to write conditional logic.)

葬花如无物 2024-07-14 23:22:38

一般来说,我会先检查意外的项目,这迫使我处理程序的异常流程。

这样,我可以在开始“设置”正常程序流程之前抛出异常/中止操作。

Generally, I'd check the unexpected items first, which forces me to deal with exceptional flow of the programme.

That way, I can throw exceptions/abort operations before I start "setting up" for the normal programme flow.

辞旧 2024-07-14 23:22:38

在大多数情况下,可读性比执行速度更重要。 因此我尝试
通过使用以下方法进行优化以便于理解:

所有“断言”检查都是预先完成的。 这保证了所有错误情况都从一开始就得到处理。 这对于空指针检查尤其重要,例如

    if(arg == null){ 
      throw new IllegalArgumentException();  // harsh (correct)
    }
    // or 
    if(arg == null){
        arg = "";  // forgiving (lazy)
    }

接下来,我尝试仅在每个 if 语句中检查 1 个条件。 而不是

    if(condition1 && condition2) {
        ...
    } else {
        ...
    }

我通常更喜欢

    if(condition1) {
        if(condition2) {
            ...
        } else {
            ...
        }
    } else {
        ...
    }

这种方法更容易设置断点,并且使逻辑更加明显。

我避免否定; 所有

    if(! condition) {
        ...a...
    } else {
        ...b...
    }

    if(condition) {
        ...b...
    } else {
        ...a...
    }

返回布尔结果的方法都应该有一个“正”名称来指示结果的含义

    boolean checkSomething(Something x){ ... }     // bad -- whats the result?
    boolean isSomethingInvalid(Something x){ ... } // better, but ...
    boolean isSomethingValid(Something x){ ... }   // best, no "mental negation"

In most situations, readability is more important than execution speed. I therefore try
to optimize for ease of understanding, by using the following approach:

All "assertion" checks are done up front. this guarantees that all erroneous cases are dealt with at the very start. this is especially important for null-pointer-checks, e.g.

    if(arg == null){ 
      throw new IllegalArgumentException();  // harsh (correct)
    }
    // or 
    if(arg == null){
        arg = "";  // forgiving (lazy)
    }

Next, i try to check for 1 condition only in each if-statement. instead of

    if(condition1 && condition2) {
        ...
    } else {
        ...
    }

i generally prefer

    if(condition1) {
        if(condition2) {
            ...
        } else {
            ...
        }
    } else {
        ...
    }

This approach is easier for setting breakpoints, and it makes the logic more obvous.

I avoid negations; instead of

    if(! condition) {
        ...a...
    } else {
        ...b...
    }

things are better rearranged to

    if(condition) {
        ...b...
    } else {
        ...a...
    }

Finally, all methods that return a boolean result should have a "positive" name that indicates what the results means:

    boolean checkSomething(Something x){ ... }     // bad -- whats the result?
    boolean isSomethingInvalid(Something x){ ... } // better, but ...
    boolean isSomethingValid(Something x){ ... }   // best, no "mental negation"
柠栀 2024-07-14 23:22:38

我的目标是以尽量减少读者必须接受的信息量的方式构建我的条件。有时,测试负面结果来证明正面结果更容易:

示例 - 测试两个日期是否相交另一个由 2 个日期组成的周期更容易编写为两个周期不相交的测试

I aim to structure my conditions in a way to minimize the amount of information the reader has to take in. Sometimes it is easier to test for the negative to prove the positive :

An example - the test to see if a period of 2 dates intersects with another period of 2 dates is easier to write as test of no intersection of 2 periods

我不是你的备胎 2024-07-14 23:22:38

如果这是一个简单的是或错误问题,那么我通常会构造一些东西,以便错误处理分支是 else 子句。 如果是或否问题(即两个分支都没有错误),则纯粹是对感觉更自然的判断。 如果在代码的核心可以执行之前必须进行很多测试,我通常会尝试构建事物,以便首先进行负面测试,并以某种方式跳过后面的代码(从函数返回、中断或继续)一个循环)。

If it's a simple yes or error question, then I usually structure things so that the error-handling branch is the else clause. If it's a yes or no question (ie neither branch is an error), it's purely a judgment call on what feels more natural. If there are a lot of tests which must be made before the heart of the code can execute, I usually try to structure things so that the negative tests come first and somehow skip the code that follows (return from the function, break or continue from a loop).

小ぇ时光︴ 2024-07-14 23:22:38

两者任一。 不过,我通常使用“消极”方法。

如果(!某事)
{

}

Either / Or. I generally use the 'negative' approach though.

if (!something)
{

}

橙味迷妹 2024-07-14 23:22:38

这有点超出了问题的范围,但通常您也希望您的方法快速失败。 出于这个原因,我倾向于在方法的顶部进行所有参数验证,即使我直到稍后在代码中才会使用该参数。 这会损害可读性,但仅限于方法非常长的情况(必须滚动屏幕才能看到它)。 当然,这本身就是一种代码味道,并且往往会被重构。

另一方面,如果检查并不简单,并且我会将其传递给另一个只是要检查它的方法,那么我不会重复代码来检查当前方法。 与大多数事情一样,有一个平衡。

This is a little out of the scope of the question, but generally you also want your methods to fail fast. For this reason I tend to do all of my argument validation at the top of the method, even if I'm not going to use the argument until later in the code. This hurts readability, but only in the case where the method is really long (have to scroll off the screen to see it). Of course, that's a code smell in itself and tends to get refactored out.

On the other hand, if the check isn't simple and I'll be passing it off to another method that is just going to check it anyway, I won't repeat the code to check in the current method. As with most things there is a balance.

层林尽染 2024-07-14 23:22:38

(上下文:Java)

READABILITY1:首先解析为较小代码块的条件

if (condition) {
  smallBlock();
} else {
  bigBlockStart();
  ........
  bigBlockEnd();
}

READABILITY2:首先进行肯定断言,因为更容易注意否定符号

有意义:使用 Assert.blabla 断言方法的所有先决条件() 并仅针对该方法执行的操作使用条件。

(Context: Java)

READABILITY1: Condition that resolves to a smaller block of code goes first

if (condition) {
  smallBlock();
} else {
  bigBlockStart();
  ........
  bigBlockEnd();
}

READABILITY2: Positive assertion goes first, as it's easier not to notice a negation sign

MAKING SENSE: Assert all the pre-conditions for a method using Assert.blabla() and use conditionals only for what the method does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文