简体   繁体   English

如何编写干净的条件语句

[英]How do I write a clean conditional statement

This may be a dumb question but what is an easy way to write a clean condition statement, for example lets say if I have a conditional statement where I only want it to happen before a block of code if it meets the requirement and if it doesn't then I want it to happen after the block of code.这可能是一个愚蠢的问题,但是写一个干净的条件语句的简单方法是什么,例如让我们说如果我有一个条件语句,我只希望它在满足要求的代码块之前发生,如果它不满足要求不是那么我希望它发生在代码块之后。 But it must happen in that order但它必须按照这个顺序发生

EDIT编辑

This code is NOT broken.. I was simply asking if there was a better way of structuring this conditional statement and I found out that putting the //random code in a helper method and combining the two if's into an else if would solve it.这段代码没有被破坏。我只是问是否有更好的方法来构造这个条件语句,我发现将 //random 代码放在一个辅助方法中并将两个 if 组合到一个 else if 中可以解决它。 See my answer below.看我下面的回答。

if(number === 250){
    // sameMethod()
}

//random code

if(number !== 250){
    // sameMethod()
}

Solution解决方案

function helper() {
    //random code
}

if(number !== 250){
    helper()
    // same code
} else {
    // same code
    helper()
}
if(number == 250){
    // sameMethod()
}

//random code

if(number != 250){
    // sameMethod()
}

For this, and based on the information at hand, I would recommend keeping the code as is.为此,根据手头的信息,我建议保持代码不变。 The way you have written this code, an if-else block would have a serious impact on the flow of your application.您编写此代码的方式,if-else 块将对您的应用程序流程产生严重影响。

Assume that randomCode is a method call, which performs the next operation:假设 randomCode 是一个方法调用,它执行下一个操作:

function randomCode() {
  this.number += 5;
}

and you start the code with the state of your application having the value of number as 245.并且您以应用程序的状态开始代码,该状态的 number 值为 245。

if ( number == 250 ) { // conditions 245 == 250 evaluates to false
  // sameMethod -> will not be executed
}

randomCode(); // increases the value of number with 5

if ( number != 250 ) { // condition 250 != 250 evaluates to false
  // sameMethod -> will not be executed
}

Just slapping an if-else, like this:只是打一个if-else,像这样:

if ( number == 250 ) { // condition 245 == 250 evaluates to false
  // sameMethod
} else {
  randomCode();
  // sameMethod -> here it will be executed, even though number now is 250. Change in behaviour
}

So, there are two things to consider: either the example code you posted was the correct flow, making it correct (but might end up in executing sameMethod twice, or not at all, since the value of number could be altered in the randomCode part, or both sameMethod and randomCode have to be executed (exactly) once, depending on that condition.因此,有两件事需要考虑:要么您发布的示例代码是正确的流程,使其正确(但最终可能会执行两次 sameMethod,或者根本不执行,因为可以在 randomCode 部分更改 number 的值,或者 sameMethod 和 randomCode 必须(恰好)执行一次,具体取决于该条件。

If so, the original (pseudo?) code was faultive, but the result would indeed come to:如果是这样,原始(伪?)代码是错误的,但结果确实会变成:

if ( number == 250 ) {
  sameMethod();
  randomCode();
} else {
  randomCode();
  sameMethod();
}

This is where monads and all that jazz show their ugly mugs.这是 monads 和所有爵士乐展示他们丑陋杯子的地方。

Assuming you are talking about java, you could for example write a runSequentially method that results in letting you write:假设您在谈论 java,例如,您可以编写一个runSequentially方法,该方法可以让您编写:

   runSequentially(() -> sameMethod(), () -> {
        // random code
   }, number != 250);

Where runSequentially will first run the first Runnable, then the second Runnable - unless the condition is false, in which case it runs the second, then the first. runSequentially 将首先运行第一个 Runnable,然后是第二个 Runnable - 除非条件为假,在这种情况下它运行第二个,然后是第一个。

In java, this is not, however, local mutable variable, checked exception, and control flow transparent which are sufficient downsides that I'm not sure this is a good idea.然而,在 java 中,这不是局部可变变量、检查异常和控制流透明,这些都是我不确定这是个好主意的足够缺点。 Especially considering that apparently execution order matters which usually suggests mutating state.特别是考虑到显然执行顺序很重要,这通常表明状态发生变化。 But, if you insist, it'd be something like:但是,如果你坚持,它会是这样的:

public static void runSequentially(Runnable a, Runnable b, boolean flipOrder) {
    if (flipOrder) { b.run(); a.run(); }
    else { a.run(); b.run(); }
}

Javascript is a lot more laissez-faire (and a totally different language; did you tag it because perhaps you were unaware that 'java' and 'javascript' are completely unrelated? It's a common mistake - in that case, disregard this bit), and doesn't suffer from the transparency issues as much. Javascript 更加自由放任(和完全不同的语言;你标记它是因为你可能不知道 'java' 和 'javascript' 完全无关?这是一个常见的错误 - 在这种情况下,忽略这一点),并且不会受到透明度问题的影响。 Javascript has no checked exceptions, javascript lets you mutate outer state (there are some WTFs in javascript-the-language about this, but that's a separate issue). Javascript 没有检查异常,javascript 允许您改变外部状态(javascript-the-language 中有一些关于此的 WTF,但这是一个单独的问题)。 The biggest issue is control flow (you can't as easily break/continue loops in the 'outer' code from within these closures).最大的问题是控制流(你不能轻易地从这些闭包中中断/继续“外部”代码中的循环)。

Going back to java for a moment, using lambdas (closures) in contexts where:暂时回到 java,在以下上下文中使用 lambdas(闭包):

  • The lambda is run 'in-line', that is, you pass the lambda to some method, and once that method returns, the lambda is 'forgotten about' by said method: That method did not store the lambda in a field, did not pass it to another thread, did not pass it to other code that is going to store it in a field or pass it to another thread). lambda 是“内嵌”运行的,也就是说,您将 lambda 传递给某个方法,一旦该方法返回,该 lambda 就会被所述方法“遗忘”:该方法没有将 lambda 存储在字段中,没有将它传递给另一个线程,没有将它传递给将它存储在一个字段中或将它传递给另一个线程的其他代码)。
  • The code in the lambda is not designed 'functional style' (eg it mutates state or does a bunch of I/O), then lambda 中的代码不是设计成“功能风格”的(例如它改变状态或执行一堆 I/O),然后

you're probably messing up.你可能搞砸了。 Lambdas really suck in that environment, those transparency issues are grating then. Lambda 在那种环境中真的很糟糕,那些透明度问题当时令人恼火。 Note that if the lambda does 'travel' (is stored / moved to another thread), that lack of transparency is in fact a great thing because those 3 'transparencies' become bizarre braintwisters - best to just not allow them.请注意,如果 lambda 确实“旅行”(存储/移动到另一个线程),那么缺乏透明度实际上是一件好事,因为这 3 个“透明度”变成了奇怪的脑筋急转弯 - 最好不要允许它们。

That's why I recommend against this, if you're writing java.这就是为什么我建议不要这样做,如果您正在编写 java.lang. But now you know how one would.但现在你知道一个人会怎么做。

Thanks for all the advice, I should've been more clear about the language since I thought this was a fairly simple solution that might work in both Java and Javascript.感谢所有的建议,我应该更清楚语言,因为我认为这是一个相当简单的解决方案,可以在 Java 和 Javascript 中工作。 I ended up just putting the "random code" in a helper function.我最终只是将“随机代码”放在一个辅助函数中。

function helper() {
    //random code
}

if(number !== 250){
    helper()
    // same code
} else {
    // same code
    helper()
}

Basically the idea was that, the order of which block of code that gets executed mattered depending on a fixed variable.基本上这个想法是,执行哪个代码块的顺序取决于固定变量。 It was messy without a helper function due to duplicated code so this simple solution fixed it.由于代码重复,没有辅助函数会很混乱,所以这个简单的解决方案修复了它。 Let me know if you guys think of a more clever way!如果你们想出更聪明的方法,请告诉我! Thanks谢谢

Maybe you can use the else if statements也许你可以使用 else if 语句

if(condition1){
    //method();
} else if(condition2){
    //method();
} else //whathever you want here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM