Home > Software design >  Multiple if statements are having single else part
Multiple if statements are having single else part

Time:11-29

I have four if conditions and for all four conditions else is single.

I four conditions are true they have their own result to be executed but if they all fail they should enter in else part which common for all and can be executed only once.

For example, for save button all four fields should have values if not, respective field will throw an error and stop saving form further.

c.save = function () {

if(a == '' || a == undefined){
    throw an error for a
}else
if(b == '' || b == undefined){
    throw an error for b
}else
if(c == '' || c == undefined){
    throw an error for c
}else
if(d == '' || d == undefined){
    throw an error for d
}else
    c.data.save = true;
}

CodePudding user response:

You could use a bool to check if all if statements have failed.

bool someBoolean = true;

if(a == true) {
    // code to execute
    someBoolean = false;
}
else if(b == true) {
    // code to execute
    someBoolean = false;
}
else if(c == true) {
    // code to execute
    someBoolean = false;
}
else if(d == true) {
    // code to execute
    someBoolean = false;
}

// check if the bool is still true
if(someBoolean) {
    // code to execute if all if statements failed
}

And then all you have to do is set the bool back to it's original state to use it again.

  • Related