Good morning. I was dead from a hangover and recovered with EVE I will write an article.
There is an "if statement" in the syntax that is indispensable for programming, Are you writing verbosely? Let's look back. When refactored, To notice that there is an if statement that can be written smarter Isn't there several times?
Now, I would like to introduce redundant patterns and smart patterns.
true
== true
This is a condition that beginners tend to do.
In the if statement, the judgment is true / false by default, so if you write == true
true
== true == true
It will have a meaning like.
Of course, I want to write if true {}.
if true {
}
if 100 >= 50 {
} else if 100 < 50 {
}
>>
if 100 >= 50 {
} else {
}
It's pretty easy to describe, but when it comes to complicated conditions You can see some if statements that have similar descriptions.
Nine balls with only one heavy weight, How can I find out with the least number of times when I want to find it on a balance? You can tell it in two times, but how many times did you do it?
if left(3) > right(3) {
if left(1) > right(1) {
//Distinguishable
}
} else {
if left(1) > right(1) {
//Distinguishable
}
}
The motivation here is to make you think that ** everything must be included in the conditional expression . Nine balls do not have to be all weighed. "Three to put on the left" "Three to put on the right" " Three not to put **" Actually, the existence of these ** three things that cannot be put on ** is important for writing smart conditional expressions. It can be identified as a comparison target without weighing it.
For patterns that do not use else if ・ When you want to improve readability ・ When simply conditional expression cannot be else if there is.
if A == A {
} else if B == B {
}
>>
if A == A {
} else {
if B == B {
}
}
I couldn't think of a suitable pattern, In some cases, it may be easier to write an if statement inside else instead of else if.
//When playing AorBorC
if A == A {
} else if B == B {
}
>> //Can't catch C
if A == A {
} else {
if B == B {
//Processing that you want to add only to B
}
//Common processing
}
if A == A {
}
if B == B {
}
if C == C {
}
When playing AorBorC, it is not recommended to write three ifs like this. The reason is ** because extra processing runs **. By writing other conditions in the else statement, the subsequent processing will not run when a match is made. However, by making the if statement independent, even if the readability is improved. ** Performance ** will drop. I don't want the computer to do any extra processing.
What did you think? Of these, the one I wanted you to incorporate most ** Example of conditional expression for weight ** is. If you can master this, the conditional expression will be pretty smart. I'm glad if you can use it as a reference.