Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain of OR conditions in if statement [closed]

Tags:

c

if-statement

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?

like image 509
Marek Čačko Avatar asked May 04 '15 09:05

Marek Čačko


2 Answers

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.

like image 71
datenwolf Avatar answered Sep 19 '22 19:09

datenwolf


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.

like image 34
acraig5075 Avatar answered Sep 18 '22 19:09

acraig5075