命令su 对不起
Recently, I came across a programming piece that put forth a rather controversial stance against the use of a basic if-else
control flow.
最近,我遇到了一个编程文章,该文章对使用基本的if-else
控制流提出了颇有争议的立场。
I’m specifically going to respond to the article “Stop Using If-Else Statements,” which offered some misleading programming advice right from its (clickbait) title.
我将特别回应文章“ 停止使用If-Else语句 ”,该文章从其(clickbait)标题中提供了一些误导性编程建议。
Subsequently, I’ll walk you through a few common mistakes that developers make when using if-else
statements and how to fix them.
随后,我将向您介绍开发人员在使用if-else
语句时所犯的一些常见错误以及如何解决它们。
那篇文章有什么问题? (What Was Wrong About That Article?)
The piece made sweeping claims by calling
if-else
statements evil. It went on to show awfully wrong use cases of the most basic programming control flow.该作品通过将
if-else
声明称为邪恶而大肆宣传。 它继续显示了最基本的编程控制流程的严重用例。The complex
if-else
clauses the author wrote not only did way too much work but were also laughably wrong. Addingthrow
statements in everyif
condition and putting an unnecessaryelse
block at the end made no sense.作者编写的复杂的
if-else
条款不仅做得太多,而且还可以笑得很错。 在每个if
条件中添加throw
语句,并在末尾放置不必要的else
块是没有意义的。- To add to the misery, the bloated solution suggested creating a class for every single state condition (with confusing naming conventions), thereby adding unnecessary abstraction. 为了增加痛苦,这个the肿的解决方案建议为每个状态状态创建一个类(使用令人困惑的命名约定),从而增加不必要的抽象。
- Introducing more than 200 lines of code for a mere ten lines of conditional logic defies the basic coding principle: Keep it simple and stupid. 仅用十行条件逻辑就引入200行以上的代码违反了基本的编码原理:保持简单和愚蠢。
Ultimately, the final solution of the article contradicted its own title. It simply delayed the use of
if-else
conditions by not placing it at the top level of the code. Despite being a good practice, this was not even mentioned in the whole story.最终,本文的最终解决方案与其标题冲突。 它只是通过将
if-else
条件置于代码的最顶层来延迟使用它。 尽管是一种很好的做法,但整个故事中甚至都没有提到。
The sad part is such misleading titles can build misconceptions in the heads of junior programmers. Yes, a rare few readers who praised the article were the ones who’d just started out programming or were about to.
可悲的是,这样的误导性标题可能会在初级程序员的脑海中产生误解。 是的,很少有人赞扬这篇文章的读者是刚开始编程或将要开始编程的人。
In summary, the article was like a code with obvious bugs. Instead of fixing the root cause of the problem, it put the blame on the whole if-else
paradigm, showed a replacement that wasn’t like-for-like, and recommended using that for all programming solutions.
总而言之,本文就像是带有明显错误的代码。 它没有解决问题的根本原因,而是将责任归咎于整个if-else
范式,展示了一个并非“按样”的替代品,并建议在所有编程解决方案中使用该替代品。
如何优雅地使用if-else语句? (How to Use if-else Statements Elegantly?)
I’d like to declare that if-else
statements aren’t bad. It’s the way that you use (or misuse) them that could lead to messy code.
我想声明if-else
语句还不错。 使用(或滥用)它们的方式可能会导致凌乱的代码。
There are no one-size-fits-all solutions in programming. Similarly, there aren’t any bad practices when using if-else
or else-if
conditions.
编程中没有万能的解决方案。 同样,使用if-else
或else-if
条件时也没有任何不良做法。
Of course, using else
statements should be done carefully, as it's difficult to predict the scope of it. If any condition besides the if
clause goes into else
, that might not be what you actually want.
当然,应谨慎使用else
语句,因为很难预测其范围。 如果除了if
子句之外还有其他条件进入else
,则可能不是您真正想要的。
If you force yourself to look for workarounds for the basic if-else
flow, you’ll only get bogged down with unnecessary boilerplate code and abstraction.
如果您强迫自己寻找基本的if-else
流解决方法,则只会陷入不必要的样板代码和抽象的泥潭。
Yet, there are some instances where I’ve seen and used if-else
statements in the wrong fashion across different languages.
但是,在某些情况下,我在不同语言之间以错误的方式查看和使用了if-else
语句。
给变量赋值时避免if-else (Avoid if-else When Assigning Value to a Variable)
Once upon a time, I did write something like this in Java (though I’m using Swift in the examples below for the sake of brevity):
很久以前,我确实用Java写过这样的东西(尽管为了简洁起见,我在下面的示例中使用Swift):
var num : Int!if someCondition{
num = 10
}
else{
num = 20
}
While it might not seem bad, you could easily end up inverting or tweaking the conditional logic to give a whole new meaning. The branching logic also brings a little code duplication, as we’re assigning the variable num
in multiple blocks, which is not necessary.
尽管它看起来似乎还不错,但是您可以轻松地反转或调整条件逻辑以给出全新的含义。 分支逻辑还带来一些代码重复,因为我们在多个块中分配了变量num
,这是不必要的。
Thankfully, we can use the ternary operator, which is like an if-else
statement in a single line:
幸运的是,我们可以使用三元运算符,就像单行中的if-else
语句if-else
:
num = isCondition ? 10 : 20
Alternatively, for some use cases, you could also set default values at variable declaration time to remove the use of else
.
另外,对于某些用例,您还可以在变量声明时设置默认值,以取消使用else
。
As a dynamically typed language, Python requires you to assign values during declaration. So, using the scenarios above is rather obvious there:
作为一种动态类型化的语言,Python要求您在声明期间分配值。 因此,在上面使用上述方案非常明显:
#Python
num = 10 if isCondition else 20
添加提早退出条件以避免其他情况 (Add Early Exit Conditions to Avoid else Part)
Often, the use of else
in blocks with multiple ifs
and else-ifs
is to handle default scenarios and deal with errors.
通常情况下,使用else
与多个块ifs
和else-ifs
是处理默认场景和处理错误。
We all must have written blocks like the following:
我们所有人都必须具有如下所示的代码块:
if someBoolean {
// ...
} else {
throw Exception("xxxx")
}
The else
part is like a fail condition that we can easily put at the start of the control flow:
else
部分就像是失败条件,我们可以轻松地将其放在控制流的开头:
if !someBoolean{
throw MyException()
}
No wonder Swift provides us with a guard let
statement to add an early fail condition in case anything is wrong. This is really handy with nested if
conditionals.
难怪Swift会为我们提供一个guard let
语句,以在发生任何错误时添加早期失败条件。 if
有条件的if
使用嵌套非常方便。
将长条件提取到函数中 (Extract Long Conditionals Into Functions)
When you’re dealing with if-else
blocks, conditional statements that involve binary operators are needed at times. &&
and ||
operators are useful for addressing specific conditions and reducing the amount of nested if
blocks.
在处理if-else
块时,有时需要涉及二进制运算符的条件语句。 &&
和||
运算符可用于解决特定条件并减少嵌套if
块的数量。
But it can easily get out of hand and turn into a long, unreadable if
condition.
但它可以很容易失控,并转成一个长,不可读的if
条件。
Here’s a look at what happens:
看一下发生了什么:
if a > 0 && isEnabled && b > 10
{...}
else
{...}
You can shorten the code above to your liking:
您可以根据自己的喜好缩短上面的代码:
- For one, if you’re using multiple booleans that aren’t mutually exclusive, replace them with enums. 例如,如果您使用的是多个不互斥的布尔值,请将它们替换为枚举。
- You can extract the condition into a separate function, thereby making things more comprehensible. 您可以将条件提取到单独的函数中,从而使事情更容易理解。
func customCondition() -> Bool{
return a > 0 && isEnabled && b > 10
}
Now, simply pass on the function above in the if
condition:
现在,只需在if
条件中传递上面的函数:
if customCondition()
{...}
else
{...}
结论 (Conclusion)
Remember, if-else
statements aren’t bad and you cannot ever eliminate them from your codebase.
请记住, if-else
语句还不错,并且您永远无法从代码库中删除它们。
But you can make your life easier by ensuring that there’s no code duplication and keeping the if-else
blocks interrelated (not mutually independent conditions).
但是,通过确保没有代码重复并保持if-else
块相互关联(而不是相互独立的条件),可以使您的生活更轻松。
That’s it for this one. Thanks for reading.
这就是它了。 谢谢阅读。
翻译自: https://medium.com/better-programming/sorry-if-else-statements-arent-bad-at-all-472c9841eea
命令su 对不起