Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-else structure

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

like image 994
Halo Avatar asked Apr 07 '10 07:04

Halo


1 Answers

I don't see a big problem with how you write it now. I do recommend using curly braces even for single statement if-blocks. This will help you avoid mistakes in case you have to add more code lines later (and might forget to add the curly braces then). I find it more readable as well. The code would look like this then:

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

    if (z) {
       do something
    } else if (q) {
       do something
    }
} else {
    do something
}
like image 92
dafmetal Avatar answered Oct 11 '22 02:10

dafmetal