Too many if statements...

zizi21 used Ask the Experts™

Is there a way of writing the code if there is too many "ifs"?

if(ssomething != null)
do this
if(anotherthing != null)
do that
if(thirdthing != null)
do ...

thanks ...
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You could use a switch block which allows you to execute a given code block based on a particular case being true.

Here's a primer:
If you can't use a switch for some reason, you can also use the fact that AND evaluates left to right to remove the ifs:

boolean ok = true ;

ok = (a != null) && doSomething1(a) ;
ok = (b != null) && doSomething2(b) ;
ok = (c != null) && doSomething3(c) ;

For this pattern you generally make the doSomethings() return boolean instead of void.

You can even chain the ok values if you want to be a bit fancier:

ok = (a != null) && doSomething1(a) && ok ;
ok = (b != null) && doSomething2(b) && ok ;
ok = (c != null) && doSomething3(c) && ok ;

ok only true at the end if all 3 succeeded.


ok = ok && (a != null) && doSomething1(a) ;
ok = ok && (b != null) && doSomething2(b)  ;
ok = ok && (c != null) && doSomething3(c)  ;

Only does each step if the previous one succeeds.

The way your pseudo-code above is presented, the ifs are all discrete - one has no bearing on the subsequent ones. So you already have the most efficient model for that. Would be different if the conditions were the same in all three cases.
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.


sorry for not explaining in more detail earlier..

if((str = somefunction != null)
      a = somevalue;            
  return null;

you can also return a boolean value. the problem is that you need to do it for many variables and at times, that lengthens the code .. .. thought maybe, there is a simpler way ...
Ah then that's different.

You could use the ternary operator in the right context : var = condition ==red?green:blue;



Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial