Categories
apple ios

Sorry, If-Else Statements Aren’t Bad at All

Once upon a time, I did write one thing like this in Java (although I’m the usage of Swift within the examples underneath for the sake of brevity):

var num : Int!if someCondition{ 
num = 10
}
else{
num = 20
}

While it could no longer appear dangerous, you must simply finally end up inverting or tweaking the conditional good judgment to offer an entire new that means. The branching good judgment additionally brings just a little code duplication, as we’re assigning the variable num in a couple of blocks, which isn’t essential.

Thankfully, we will be able to use the ternary operator, which is like an if-else commentary in one line:

num = isCondition ? 10 : 20

Alternatively, for some use circumstances, you must additionally set default values at variable declaration time to take away the usage of else.

As a dynamically typed language, Python calls for you to assign values right through declaration. So, the usage of the situations above is moderately obtrusive there:

#Python
num = 10 if isCondition else 20