Answer the question
In order to leave comments, you need to log in
What is the best way to write if conditions?
Let's say I have a function/method that returns a boolean value. First there is a condition check, and then some logic. How best to describe?
Option 1:
if(foo == bar && foo >= 1) {
//Логика
return true;
}
return false;
if(foo != bar) return false;
if(foo < 1) return false;
//Логика
return true;
Answer the question
In order to leave comments, you need to log in
It's better to write like this:return (foo == bar && foo >= 1) ? true : false;
The second one is better, because in the first { one can { get { a billion { levels of { nesting } } } } }
1. I agree that you need to leave as quickly as possible. So something like this is better:
if(foo != bar || foo < 1) {
return false;
}
// логика
return true;
// кол-во товара в корзине != кол-ву товара при котором делается скидка
if(foo != bar){
return false;
}
// если корзина вообще пуста
if(foo < 1){
return false
}
// применение скидки к заказу
return true;
if (!(foo == bar && foo >= 1)) return false;
The approach is called "early exit" and is intended to improve readability.
You must end the function as soon as possible. Next, there may be the creation of large and complex objects, and then a crap and a null parameter, and you have already created everything unnecessary.
You can also use Short-circuit evaluation :
res = true
res &&= (foo == bar)
res &&= (foo != baz)
if (res) some_logic1
res &&= (foo >= 1)
if (res) some_logic2
return res
res = false
if (foo == bar && foo != baz) {
some_logic1
if (foo >= 1) {
some_logic2;
res = true
}
}
return res
It's better not to write return in the condition at all, one return at the end of the function.
And the conditions should be combined if they are logically united by a common meaning. Those. they can potentially be moved to a separate function.
Just written
First, it is better to write the "normal" passage of the condition (that is, when the algorithm goes according to the "expected/acceptable" scenario). And then to make branches on "deviations from the norm."
Of course, this advice is not always applicable :)
Better from whose point of view?
If a person, then you have already written a lot here.
I program controllers, there is a different approach and a different understanding of "better" - in doubtful cases, I write several options and look at the assembler code. It is him (as one can imagine, somewhat simplifying reality) that the CPU will perform.
Yes, there is also the point of view of the optimizing compiler. His point of view is precisely expressed in assembly code.
As a rule, "boring and flat" is better optimized - keep it simple, stupid. :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question