Alex Rivera | Logout

if-else structure

Asked 2010-04-07T07:12:47.577
12

I have these long statements that I will refer to as x,y etc. here. My conditional statements' structure goes like this:

if(x || y || z || q){
    if(x)
       do someth
    else if (y)
       do something

    if(z)
       do something
    else if(q)
       do something
}
else
    do smthing

Is there a better, shorter way to write this thing? Thanks

Edit
Report

2 Answers

1

Maybe this is a little easier to read. But now you will perform one extra check. If it is not mission critical code then maybe you can use the following:

if (x)
  do something;
else if (y)
  do something;

if (z)
  do something;
else if(q)
  do something;

if !(x || y || z || q)
  do something completely different.
answered 2010-04-07T07:18:05.003
0

Can you make some assumptions about x,y,z,q? e.G. just one of them can be true. Than you could see it as a State

enum State {
X{
  void doSomething(){
    doItTheXWay();
  }  
},
Y{
  void doSomething(){
    doItTheYWay();
  }  
},
Z{
  void doSomething(){
    doItTheZWay();
  }  
},
Q{
  void doSomething(){
    doItTheQWay();
  }  
};
  void doSomething(){

  }
}

and in your code where you used the if statements

you could assign a state and just do the right thing

State state = getAState();
state.doSomething();

In case you don't like enums State could be an Interface and X to Q could be implementing classes. The benefits in this case are in multiple usage of the same if else construct. Say some codelines later you would begin with

if(x)
  do_the_next_thing_with_X();
...

or you could just extend your enum with another function and make one single call

state.doTheNextThing();
answered 2012-08-11T23:23:20.613

Your Answer