In my code I have a if statement, which looks like:
if(someFunction1(a) || someFunction2(b->b1,c) || *d == null || somefunction3(e) > f * g || !e->e1 || ...){
return 0;
} else {
do_something;
}
In my code with real variable and function names are conditions nearly in three lines and it looks very overlook. So I decided to rewrite it into form:
if(someFunction1(a)){
return 0;
} else if(someFunction2(b->b1,c)){
return 0;
} else if(*d == null){
return 0;
} else if(somefunction3(e) > f * g){
return 0;
} else if(!e->e1){
return 0;
} else if(...){
return 0;
} else{
do_something;
}
Is there any argument why I should not do it?
From a purely semantic-syntactical point of view there's no effective difference between them. But if readability is your concern, why don't you use the "datenwolf" formatting style – I came to develop that style over the course of my past 5 projects or so:
if( someFunction1(a)
|| someFunction2(b->b1,c)
|| *d == null
|| somefunction3(e) > f * g
|| !e->e1
|| ...
){
return 0;
} else {
do_something;
}
Do you see how beautiful everything lines up? It really looks like a tube the program is falling down through until it hits a met condition. And if you have &&
it looks like a chain of operations that must not be broken.
As you're asking because of readability you may want to rearrange the long conditional into predicate variables that say why zero must get returned.
bool unnecessary = someFunction1(a) || someFunction2(b->b1,c);
bool beyondTolerance = somefunction3(e) > f * g;
bool invalidInput = *d == nullptr || !e->e1;
if (unnecessary || beyondTolerance || invalidInput)
return 0;
else
...
This is Martin Fowler's Decompose Conditional refactoring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With